UIWebview enable cookies(UIWebview 启用cookies)
问题描述
我正在尝试通过 UIWebView
访问需要 cookie 的特定 URL,但我无法访问它,因为 cookie 被禁用.所以我做了以下事情:
I am trying to access a specific URL that requires cookies through UIWebView
but I can not access it because cookies are disabled. So I did the following:
启用 cookie:
Enabled cookies:
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
[cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
创建 NSURLConnection
并从响应中提取 cookie:
Created NSURLConnection
and extracted cookies from response:
NSArray *cookies = [ NSHTTPCookie cookiesWithResponseHeaderFields: [ httpResponse allHeaderFields ] forURL:response.URL];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies: cookies forURL: response.URL mainDocumentURL:nil];
但这都没有帮助.但是,如果我在 safari 中启动 URL,它会成功加载,之后我也可以在 UIWebView
中加载相同的 URL.你能帮我解决这个问题,我怎样才能为 UIWebView
启用 cookie?
But neither of this didn't help. However if I launch the URL in safari it loads successfully and after that I can load the same URL in UIWebView
too. Could you help me with this, how can I enable cookies for UIWebView
?
提前致谢
推荐答案
创建NSURLRequest
后,将sharedHTTPCookieStorage中的所有cookie复制到NSURLRequest
:
After create a NSURLRequest
, copy all cookies in sharedHTTPCookieStorage to 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"];
}
}
}
这篇关于UIWebview 启用cookies的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:UIWebview 启用cookies
基础教程推荐
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01