我想从 http://mycompany.com/jsonpage1..etc 获取JSON。网络服务器需要初始登录 http://mycompany.com/login,然后为用户维护cookie。如何使用 NSURLCredentialStorage 获取此行为,而无需每次都要求登录?这是使用 NSURLCredential Storage 的非工作代码
- (IBAction)getJSON:(id)sender
{
// [self establishSession];
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);
}
您可以尝试AFNetworking库和子类AFHTTPClient,您可以在其中封装每个请求的身份验证。