4

我正在尝试访问需要 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。你能帮我解决这个问题,我怎样才能启用cookies UIWebView

提前致谢

4

1 回答 1

6

创建后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"];
        }
    }
}
于 2013-03-07T09:12:39.927 回答