如何使用一个NSURLConnection对Web服务器进行多个经过身份验证的请求?

时间:2012-08-19 14:58:48

标签: ios cookies webserver nsurlconnection nsurlrequest

我想从http://mycompany.com/jsonpage1..etc获取JSON。 Web服务器需要初始登录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);

}

1 个答案:

答案 0 :(得分:0)

您可以尝试AFNetworking库和子类AFHTTPClient,您可以在其中为每个请求封装您的身份验证。