在请求的时候加
//支持cookie
[urlRequest setHTTPShouldHandleCookies:YES];
表示该请求支持cookie
在响应中取得cookie,并保存
- (void)connection:(NSURLConnection *)connection // IN
didReceiveData:(NSData *)data // IN
{
NSString *reply = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSNumber *statusInfo =[[reply JSONValue] valueForKey:@"status"] ;
NSLog(@"reply=====%@",reply);
[reply release];
if ([statusInfo intValue]==1) {
//保存cookie
NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)self.responseCopy;
NSDictionary *fields = [httpResponse allHeaderFields ];
NSLog(@"response头内容===%@",[fields description]);
//取得cookie
if (self.cookie == nil) {
NSString *tempCookie =[[NSString alloc] initWithString: [fields valueForKey:@"Set-Cookie"]];
self.cookie=tempCookie;
[tempCookie release];
tempCookie=nil;
}
else{
self.cookie = [fields valueForKey:@"Set-Cookie"];
}
NSLog(@"cookie = %@",self.cookie);
//接受cookie
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
NSLog(@"写入后:%@",[[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies]);
}
至此cookie已经成功保存到[[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies]中
注意cookie是有一个实效时间的,如果那个时间没有设定的话,默认的是浏览器打开期间
下边是如何在请求中加入cookie
// 从 URL 中载入一个 html 页面
for (NSHTTPCookie *tempcookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies]) {
NSLog(@"numberOfCookies_get :Namehome: %@ : Value: %@", tempcookie.name, tempcookie.value);
self.cookie=[[[[[tempcookie.name stringByAppendingString:@"="]stringByAppendingString:tempcookie.value] stringByAppendingString:@"; "] stringByAppendingString:@"path="]stringByAppendingString:tempcookie.path];
}
NSLog(@"webView.cookie=====in webview====%@",self.cookie);
NSURL *url = [NSURL URLWithString:@"http://aa/bb/"];//这里是需要cookie的网址
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest addValue:self.cookie forHTTPHeaderField:@"Set-Cookie"];
[self.WebView loadRequest:urlRequest];
这样从开始获得cookie,到应用cookie,整个过程就完整了。