我想从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);
}