gpt4 book ai didi

ios - UIWebview 启用 cookie

转载 作者:可可西里 更新时间:2023-11-01 05:31:16 24 4
gpt4 key购买 nike

我试图通过 UIWebView 访问需要 cookie 的特定 URL,但我无法访问它,因为 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,它会成功加载,之后我也可以在 UIWebView 中加载相同的 URL。你能帮我解决这个问题吗?如何为 UIWebView 启用 cookie?

提前致谢

最佳答案

创建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"];
}
}
}

关于ios - UIWebview 启用 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12069622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com