NSMutableURLRequest proper posting

亡梦爱人 提交于 2019-12-23 03:50:18

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/3670029/nsmutableurlrequest-proper-posting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!