假设你有一个 NSHTTPURLResponse,你可以得到一个像这样的 cookie 数组:
NSDictionary * headers = [(NSHTTPURLResponse *)response allHeaderFields];
NSArray * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:headers forURL:response.URL];
response
NSHTTPURLResponse在哪里。
您将在 NSURLConnectionDelegate 的这 2 个方法中获得 NSURLResponses
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
NSHTTPCookie 有一个properties
返回 的属性NSDictionary
,所以你可以保存它们。然后可以使用相同的字典创建它们-initWithProperties:
要发送它们,您需要为 a 的 Cookie 标头创建自己的字符串NSURLRequest
。就像是:
NSMutableString * cookieString = [[NSMutableString alloc] init];
for (NSHTTPCookie * cookie in myLoadedCookies){
[cookieString appendFormat:@"%@=%@; ", cookie.name, cookie.value];
}
[request setValue:cookieString forHTTPHeaderField:@"Cookie"];
[cookieString release];
request
一个在哪里NSMutableURLRequest
。
您还应该确保停止 iOS 管理 cookie 本身:
[request setHTTPShouldHandleCookies:NO];