UIWebview 启用cookies

UIWebview enable cookies(UIWebview 启用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

    基础教程推荐