iOS-WKWebView攜帶cookie發送http請求,cookie失效

來源:互聯網
上載者:User

標籤:

發送請求代碼:

NSString *testUrl = @"http://10.22.122.7:8081/test2_action/view_index"; NSURL *url = [NSURL URLWithString:testUrl]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60]; NSString *value = [NSString stringWithFormat:@"WAP_0000E86BEBFC4514987AE63ACF9D19Dd=123",]; [request setValue:value forHTTPHeaderField:@"Cookie"]; [_webView loadRequest:request];

結果:網頁內跳轉,cookie失效

問題原因分析:

WKWebView在第一次載入的時候攜帶cookie,然後在WKWebView中產生頁面跳轉的時候WKWebView自動清除了cookie,導致使用者需要二次登入。

解決辦法:

建立webView對象的時候,把cookie放到WKWebView中,實現所有請求都攜帶cookie。

以下是實現代碼:(這裡的cookie第一次請求的時候不起作用,在h5頁面內再次跳轉的時候才會起作用,不明原因)

WKUserContentController* userContentController = [[WKUserContentController alloc] init];WKUserScript * cookieScript = [[WKUserScript alloc]initWithSource: [NSString stringWithFormat:@"document.cookie = ‘WAP_COOKIE_ENABLE=1‘;document.cookie = ‘WAP_0000E86BEBFC4514987AE63ACF9D19Dd=%@‘;",user.WAP_0000E86BEBFC4514987AE63ACF9D19Dd]                            injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];[userContentController addUserScript:cookieScript];WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];configuration.userContentController = userContentController;[configuration.userContentController addScriptMessageHandler:self name:@"Redirect"];self.webView = [[[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration] autorelease];

注意點:

1、建立webView的時候加了cookie,一開始發送請求的時候也要加上cookie,

2、保證一開始發送請求的cookie跟這裡的cookie是一致的。

 

iOS-WKWebView攜帶cookie發送http請求,cookie失效

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.