38

I'm getting a HttpResponse from a server when checking if a username or password is correct. When I load the url in a webview I want the webView to have the cookie (the answer I get with postData() stored in the webView. I want the webView to pickup the cookie and load the url with that cookie stored in the webview.

I'm getting the response through.

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 loadUrl with:

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

I guess I'm not really managing a cookie and I have no idea how to do so. Any suggestions or solutions?

Amit Basliyal
  • 840
  • 1
  • 10
  • 28
Joakim Engstrom
  • 6,243
  • 12
  • 48
  • 67
  • refer this http://stackoverflow.com/questions/2566485/webview-and-cookies-on-android – neeraj t Sep 27 '12 at 14:22
  • Android documentation for webView CookieManager is https://developer.android.com/reference/android/webkit/CookieManager – QMaster Nov 30 '19 at 12:22
  • Does this answer your question? [Android WebView Cookie Problem](https://stackoverflow.com/questions/1652850/android-webview-cookie-problem) – D Nikolz Aug 25 '21 at 14:32

5 Answers5

33

It's quite simple really.

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

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

700 Software
  • 85,281
  • 83
  • 234
  • 341
  • Finally I found a solution for this, many thanks George. Quick question. Do you know what would be the duration of the cookie in this way? or what would be the parameter to set it? – JohnA10 Nov 15 '16 at 20:13
  • 1
    This is a session cookie, so it probably expires when the application is closed. To make the cookie permanent, you would add the Expire rule to set a definite end date. Search online for how to add Cookie Expiration. If you have issues putting this in place, feel free to [ask](http://stackoverflow.com/questions/ask) a detailed question with a code sample. – 700 Software Nov 15 '16 at 20:34
  • Note `setCookie()` accepts only a single cookie value, for multiple cookies check https://stackoverflow.com/a/55159942/12173451 – hldev Jan 24 '23 at 17:07
18

Couple of comments which I found out from my experience and gave me headaches:

  1. http and https urls are different. Setting a cookie for http://www.example.com is different than setting a cookie for https://www.example.com
  2. A slash in the end of the url can also make a difference. In my case https://www.example.com/ works but https://www.example.com does not work.
  3. CookieManager.getInstance().setCookie is performing an asynchronous operation. So, if you load a url right away after you set it, it is not guaranteed that the cookies will have already been written. To prevent unexpected and unstable behaviours, use the CookieManager#setCookie(String url, String value, ValueCallback callback) (link) and start loading the url after the callback will be called.

I hope my two cents save some time from some people so you won't have to face the same problems like I did.

giorgos.nl
  • 2,704
  • 27
  • 36
  • 1
    The documentation says that the setCookie method with the callback parameter is asynchronous, but it doesn't say that about the one without the callback parameter. Is that one asynchronous? If so, how do you know that? – stepanian Feb 07 '19 at 06:11
  • Setting the cookies without the callback was inconsistent for me. The cookies were sometimes set right away, sometimes not. Trial & error, having the chrome debug tool open in the desktop Chrome browser and triggering a toast in my app which was displaying the currently set cookies of my webview. – giorgos.nl Feb 07 '19 at 09:14
  • Got it. Thanks. I ended up just passing a URL parameter to the server and having the server handle the logic and cookie setting. – stepanian Feb 07 '19 at 21:48
5

You should use it with some loop if you have few items with cookies (like in my case):

val cookiesList = listOf("key1=someValue1", "key2=someValue2", "key3=someValue3")
cookiesList.forEach { item ->
 CookieManager.getInstance().setCookie("http://someHost.com", item)
}

You can't use it like:

CookieManager.getInstance().setCookie("http://someHost.com", "key1=someValue1;key2=someValue2;key3=someValue3")
Lucas B.
  • 489
  • 5
  • 15
Djek-Grif
  • 1,391
  • 18
  • 18
5

You may want to take a look of how I am setting the a webview cookie at :

Android WebView Cookie Problem

Where in my answer you could see how I'm handling this like:

val cookieManager = CookieManager.getInstance()
cookieManager.acceptCookie()
cookieManager.setCookie(domain,"$cookieKey=$cookieValue")
cookieManager.setAcceptThirdPartyCookies(view.webViewTest,true)
Samuel Luís
  • 171
  • 1
  • 7
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/24457769) – Andrii Omelchenko Oct 31 '19 at 15:42
  • Hey @AndriiOmelchenko thanks for the tip, I'm quite new in this thing of trying to answer the people here... I've editer the comment, better now? – Samuel Luís Oct 31 '19 at 15:47
  • 1
    IMHO - yes, now its better. – Andrii Omelchenko Oct 31 '19 at 16:01
0

Just wanna throw another way how this can be done. Not saying it is the best, but it is a way. You can use JavaScript to set cookies as well. 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 will have to reload the webView. If anyone knows how to fix that, please comment.

Sermilion
  • 1,920
  • 3
  • 35
  • 54