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
You'll probably want to take a look at this solution: Android WebView Cookie Problem
Couple of comments which I found out from my experience and gave me headaches:
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
https://www.example.com/
works but https://www.example.com
does not work.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.
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)
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.
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.
You should use it with some loop if you have few items with cookies (like in my case):
val cookies = "key1=someValue1;key2=someValue2;key3=someValue3"
val cookiesList = cookies.split(";")
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")