开发者

NSMutableURLRequest proper posting

So I am trying to log into my site using an NSMutableURLRequest which presents the credentials via a post. As开发者_运维问答 a noobie, I have some questions about the functionality of this method to make sure I am understanding it.

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@&TARGET=%@",LoginId,LoginPwd,target];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setHTTPShouldHandleCookies:YES];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://somelogin.mycomp.verify.fcc"]]];
//[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

Now this will automatically handle any redirects via the delegate method correct? It will also collect any cookies along the way? Also, should I be using an asynchronous request instead? Thanks!

UPDATE: So I have deduced that some of the cookies are being ignored by the request and subsequent redirects. Does anyone know why that may be happening?


you can do something like this when logging in synchronously... the code is not perfect, but this is the general idea.

look here for documentation

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/AuthenticationChallenges.html#//apple_ref/doc/uid/TP40009507-SW1

// credentials set here
NSURLCredential *creds = [NSURLCredential credentialWithUser:LoginId password:LoginPwd
                                           persistence:NSURLCredentialPersistenceForSession];

NSURLProtectionSpace *protectionedSpace = [[NSURLProtectionSpace alloc]
  initWithHost:@"mycomp.verify.fcc"
  port:8443
  protocol:@"https"
  realm:nil
  authenticationMethod:nil];


[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:creds
                                            forProtectionSpace:protectionedSpace];

// removed credentials from line...
NSString *post = [NSString stringWithFormat:@"TARGET=%@",target];

here is a tutorial that does it asynchronously

http://iosdevelopertips.com/networking/handling-url-authentication-challenges-accessing-password-protected-servers.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜