【发布时间】:2012-08-20 20:37:04
【问题描述】:
我想从http://mycompany.com/page1...http://mycompany.com/page2 获取JSON...在网络服务器端,它需要初始登录http://mycompany.com/login,然后为用户维护一个cookie。如何使用 NSURLConnection 获得这种行为,而不必每次都要求登录?这是使用 NSURLCredential 存储的非工作代码。我是否需要在登录时从 web 服务获取 cookie,然后将其与以后的请求一起发送?我为此苦苦挣扎了一段时间,所以请您澄清一下您的答案。
- (IBAction)getJSON:(id)sender
{
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user"
password:@"pass"
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost:@"myCompany.com"
port:0
protocol:@"http"
realm:nil
authenticationMethod:nil];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential
forProtectionSpace:protectionSpace];
//////////GET JSON//////////////
NSError *error;
NSURL *url = [NSURL URLWithString:@"http://mycompany.com.jsonpage1"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
//I am NOT getting JSON in this delegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@",responseString);
}
【问题讨论】:
-
我会在每次应用启动时通过自动发送用户的登录信息(如果他们希望将其保存在应用中)为用户获取 cookie。
-
@Jeremy,所以,听起来我需要先获取 cookie,然后将此 cookie 与请求一起发送。你知道如何发送带有 URLRequests 的 cookie 吗?谢谢
标签: ios cookies nsurlconnection session-cookies nsurlcredential