NSMutableURLRequest正确发布

时间:2010-09-08 16:48:46

标签: iphone objective-c ipad ios4

所以我想尝试使用NSMutableURLRequest登录我的网站,NSMutableURLRequest通过帖子显示凭据。作为一个noobie,我对这个方法的功能有一些疑问,以确保我理解它。

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];

现在这会通过委托方法自动处理任何重定向吗?它还会收集任何饼干吗?另外,我应该使用异步请求吗?谢谢!

更新: 所以我推断出一些cookie被请求和随后的重定向忽略了。有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:0)

在同步登录时你可以这样做......代码并不完美,但这是一般的想法。

在这里查看文档

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];

这是一个异步执行的教程

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