0

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

}
4

1 回答 1

0

阅读饼干:

请参阅在 iPhone 上管理 HTTP Cookie

设置cookie:

... 使用 cookie 属性设置字典,然后:

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:[NSDictionary dictionaryWithObjects:object forKeys:keys]];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

但请记住,会话 cookie 可能会在您的服务器上过期

于 2012-08-20T12:37:04.830 回答