我试图访问过需要使用Cookie特定的URL UIWebView
但我不能访问它,因为Cookie被停用。 所以,我做了以下内容:
启用Cookie:
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
创建NSURLConnection
和响应中提取的cookie:
NSArray *cookies = [ NSHTTPCookie cookiesWithResponseHeaderFields: [ httpResponse allHeaderFields ] forURL:response.URL]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies: cookies forURL: response.URL mainDocumentURL:nil];
但无论是这并没有帮助。 但是,如果我在Safari启动URL它成功加载之后,我可以加载在同一URL UIWebView
了。 你能帮我这个问题,我怎样可以使饼干UIWebView
?
提前致谢
创建后NSURLRequest
,在sharedHTTPCookieStorage所有Cookie复制到NSURLRequest
:
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPShouldHandleCookies:YES];
[self addCookies:cookies forRequest:request];
[_webView loadRequest:request];
并添加addCookies:forRequest
方法
- (void)addCookies:(NSArray *)cookies forRequest:(NSMutableURLRequest *)request
{
if ([cookies count] > 0)
{
NSHTTPCookie *cookie;
NSString *cookieHeader = nil;
for (cookie in cookies)
{
if (!cookieHeader)
{
cookieHeader = [NSString stringWithFormat: @"%@=%@",[cookie name],[cookie value]];
}
else
{
cookieHeader = [NSString stringWithFormat: @"%@; %@=%@",cookieHeader,[cookie name],[cookie value]];
}
}
if (cookieHeader)
{
[request setValue:cookieHeader forHTTPHeaderField:@"Cookie"];
}
}
}