如何从Webserver获取cookie并在iOS应用程序中进行维护



我想从http://mycompany.com/page1...http://mycompany.com/page2...在Web服务器端,它需要初始登录http://mycompany.com/login,然后为用户维护cookie。如何在NSURLConnection中获得这种行为,而不必每次都要求登录?以下是使用NSURLCredential Storage的非工作代码。我需要在登录时从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:

请参阅管理iPhone 上的HTTP Cookie

设置cookie:

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

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

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

上过期

最新更新