Set cookie for webView on Android

I get HttpResponse from the server, checking for the correct username or password. When I load the url in webview , I want the webview have a cookie (the answer I get with postData() stored in webview . I want the webView to load a cookie and load the url with this cookie stored in web browsing.

I get an answer.

 public HttpResponse postData() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://example.com/login.aspx"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("txtUsername", "user")); nameValuePairs.add(new BasicNameValuePair("txtPassword", "123")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); String responseAsText = EntityUtils.toString(response.getEntity()); Log.v(TAG , "Response from req: " + responseAsText); return responseAsText; } catch (ClientProtocolException e) { } catch (IOException e) { } return null; } 

And I load Url:

 webView.loadUrl("http://a_page.com/getpage.aspx?p=home"); 

I think that I do not control the cookie, and I have no idea how to do this. Any suggestions or solutions?

+15
android post cookies
Apr 19 '11 at 13:13
source share
3 answers

You'll probably want to take a look at this solution: Problem with Android Cookie Android

+8
Apr 19 '11 at 13:41
source share

It is very simple.

 String cookieString = "cookie_name=cookie_value; path=/"; CookieManager.getInstance().setCookie(baseUrl, cookieString); 

where cookieString formatted in the same way as the more traditional HTTP Set-Cookie header, and baseUrl is the site to which the cookie should belong.

+5
Jun 30 '16 at 2:06
source share

I just want to do it the other way how it can be done. Not to say that this is the best, but it is a way. You can use JavaScript to set cookies. Just override onPageFinished in WebViewClient

 new WebViewClient() { override fun onPageFinished(view: WebView, url: String) { val javascript = """document.cookie = "key=$value"""" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { view.evaluateJavascript(javascript) { s -> Timber.d("Inject: %s", s) } } else { view.loadUrl("javascript:" + javascript, null) } } } 

One thing with this approach: you have to reload the webView. If anyone knows how to fix this, please comment.

0
Nov 16 '17 at 20:59
source share



All Articles