Cookie doesn't work properly in webview in android - android

Needed datas is not written to cookies immediately in WebView. But when I wait for 10-15 seconds everything is ok.
To explain the situation, this example would be good as for me:
I open the app and login. After login, I close the app immediately. Then after I open the app again, it shows me to logout. But if I open the app after 1 minute, it shows again as logged in. For me cookies are written lately. But I cannot find solution. Please help me if you know.
I used CookieManager class but it doesn't help either.
CookieManager.getInstance().setAcceptCookie(true);

I had similar issue and I added the below code and worked.
String myURL = "https://www.yourWebPage.com";
android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.acceptCookie();
cookieManager.setAcceptFileSchemeCookies(true);
cookieManager.getInstance().setAcceptCookie(true);
cookieManager.getCookie(myURL);
Hope it helps.

I had the similar problem, what I did is to get the cookies when login and set cookies for the load url you set on webView
#Nullable
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String resourceUrl = request.getUrl().toString();
Log.e(MainActivity.TAG, "the request url :" + resourceUrl);
CookieManager cookieManager1 = CookieManager.getInstance();
// get the resourceUrl that has session
if (resourceUrl.equals("the url has session")){
String Cookies = cookieManager1.getCookie(resourceUrl);
if (Cookies != null && Cookies.contains("sessionid")){
String[] cookiesList = Cookies.split(";");
cookieManager1.removeSessionCookies(null);
for (String c : cookiesList) {
cookieManager1.setCookie("the load url", c);
}
}
}
return super.shouldInterceptRequest(view, request);
}

Related

get cookies from url in webview android

I am trying to get cookie from URl in android web view. but always get null..
here is my code
public String getCookie(WebView mWebView, String siteName,String cookieName){
String CookieValue = null;
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptThirdPartyCookies(mWebView, true);
String cookies = cookieManager.getCookie(siteName);
String[] temp=cookies.split(";");
for (String ar1 : temp ){
if(ar1.contains(cookieName)){
String[] temp1=ar1.split("=");
CookieValue = temp1[1];
break;
}
}
return CookieValue;
}
I think you need to call cookieManager.setAcceptThirdPartyCookies(mWebView, true); before the visit (loadUrl).
If the problem isn't that, I don't think you have that cookie. You can try to log cookies variable to the console for being sure the cookie is really exists.

Android Intercept a WebView request properly

My current code for intercepting a request in webview is
#Override
public WebResourceResponse shouldInterceptRequest(WebView view,
String url) {
String ext = MimeTypeMap.getFileExtensionFromUrl(url);
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
if (mime == null) {
return super.shouldInterceptRequest(view, url);
} else {
HttpURLConnection conn = (HttpURLConnection) new URL(
url).openConnection();
conn.setRequestProperty("User-Agent", userAgent);
return new WebResourceResponse(mime, "UTF-8",
conn.getInputStream());
}
}
I got this code from
The best way to intercept a WebView request in Android.
However, whenever I try to perform authentication, let's say I am loading facebook in my webview.
mWebView.loadUrl("https://www.facebook.com/");
Nothing is happening, what I noticed is that, the request headers are incomplete and also the response. Also, there are no cookies in the Sources. (I saw this when I remotely debugged the webview through Chrome).
Please correct me if I'm wrong, but I think that the incomplete headers and missing cookies is what causing the login request to fail.
Is there a way where I can modify the request and set its headers? Also for the response, should I do it too? And finally, how will I be able to have the cookies.
This question hasn't been answered for 6 months, so I don't know whether you will still need this, but maybe someone else has a similar question.
request headers are incomplete
When using HttpURLConnection you will be responsible to set any request headers, you might need, but it is as simple as setting the User-Agent, which you already did: conn.setRequestHeader(header, value) or if you want to add and not overwrite a header value: conn.addRequestHeader(header, value)
Alternatively, you could use okhttp, a HTTP client, which should add default values for headers, that are commonly expected.
there are no cookies in the Sources
When intercepting the request, you will also be in charge for handling cookies. You could store the cookie manually, by parsing the headers from the response e.g.
public WebResourceResponse shouldInterceptRequest(WebView view,
String url) {
// do your stuff
conn.connect(); // required to tell that the connection should be established
String cookie = getCookieFromConnection(conn);
// do more stuff and return WebResourceResponse
}
/**
* iterates all headers, and finds "cookie" headers
* (there could be more than one)
* #return cookie (concatenated value of all the found cookies)
* or null if no cookie has been found
*/
private String getCookieFromConnection(HttpURLConnection connection) {
String cookie = "";
Map<String, List<String>> header = connection.getHeaderFields();
List<String> cookies = header.get(COOKIE_HEADER);
if (cookies != null) {
for (String c : cookies) {
if (c != null) cookie += c + ";";
}
}
if (cookie.isEmpty()) return null;
return cookie;
}
or you could use a CookieManager, which would handle everything for you:
cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
You could will also need to handle your cookies, when using okhttp, but again you could use the CookieManager as stated above. See this docu for more details, or this stackoverflow question.
Please correct me if I'm wrong, but I think that the incomplete headers and missing cookies is what causing the login request to fail.
There is another problem, when intercepting requests in a WebView: it somehow stops loading and evaluating javascript. I found this blog by Artem Zinnatullin online, who describes this behavior, and I experienced the same behavior.
If anyone would has a solution for this, I would be very happy.

CookieManager.getCookie() returns null

I have some http requests. One of them retrieves and parse cookie from it's response. I save this cookie via CookieSyncManager and CookieManager with following code:
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeSessionCookie();
cookieManager.removeAllCookie();
String cookieString = cookie.getName() + "=" + cookie.getValue();
Log.e(getClass().toString(), cookieString);
cookieManager.setCookie(START_PAYMENT_URL, cookieString);
CookieSyncManager.getInstance().sync();
Log.e(getClass().toString(), "Get cookie: " + cookieManager.getCookie(START_PAYMENT_URL));
Both Log.e calls write same cookie. So everything looks ok.
I have different activity which contains WebView. I need to call postUrl(String url) method with some POST params and with authorization cookie. I thought that cookie is in CookieManager and everything should work great. Well. It is. But on 4.x devices only.
On 2.x devices WebView makes postUrl without cookie.
Here is activity code which contains WebView:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.payment_webview);
final String billId = getIntent().getStringExtra(INTENT_BILL_ID);
final WebView webView = (WebView) findViewById(R.id.payment_webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.e(getClass().toString(), url);
view.loadUrl(url);
return false;
}
});
String postData = "id_bill=" + billId;
Log.d(TAG, "Requesting payment URL " + START_PAYMENT_URL + " with post data: " + postData);
Log.d(TAG, CookieManager.getInstance().getCookie(START_PAYMENT_URL));
webView.postUrl(START_PAYMENT_URL, EncodingUtils.getBytes(postData, "BASE64"));
}
CookieManager.getInstance().getCookie(START_PAYMENT_URL) returns null on 2.x devices and cookie value on 4.x devices.
How to fix this problem?
Seems like I figured out what's the problem.
I just removed
cookieManager.removeSessionCookie();
cookieManager.removeAllCookie();
while I'm saving cookies.
I suppose that problem is that all methods of CookieManager work asynchronously. Probably remove cookies methods invoked after cookieManager.setCookie(START_PAYMENT_URL, cookieString); even if they called before it. So CookieManager saves cookies and after that remove cookies methods invoked.

Cookies in WebView Android

I can't read all my cookies, in my webview i can only read "PHP_AUTH_SID" named cookie, but in browser i can see all cookies. Here is my code:
super.onCreate(savedInstanceState);
CookieSyncManager.createInstance(this);
webView = (WebView) findViewById(R.id.web_login);
And this is my shouldOverrideUrlLoading() method in web view client
CookieSyncManager.getInstance().sync();
final CookieManager cookiesManager = CookieManager.getInstance();
cookiesManager.setAcceptCookie(true);
final String cookies = cookiesManager.getCookie(COOKIES_HOST);
Log.i("123123", cookies);
in LogCat i can see only: "09-13 14:05:48.139: I/123123(21188):PHP_AUTH_SID=..."
in browser:
PHP_AUTH_SID=...,
access_token=...
It seems that the output from LogCat is just cut off. Just try to debug and see the "really" content of "cookies" string.
I think you could just parse the cookies string with String[] elements = cookies.split("=")

Android CookieManager setCookie doesn't set anything

in my application, I'm getting two cookies from an HttpGet request and store them in the CookieManager like this:
//Clear old cookies
CookieManager.getInstance().removeAllCookie();
CookieSyncManager.getInstance().sync();
//Save the two cookies: auth token and session info
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
String cookieString = cookie.getName() + "=" + cookie.getValue() + "; Domain=" + cookie.getDomain();
CookieManager.getInstance().setCookie("http://alpha.mydomainname.com", cookieString);
}
System.out.println(CookieManager.getInstance().hasCookies()); //Prints false in 2.3, true in 4.0.3
CookieSyncManager.getInstance().sync();
System.out.println(CookieManager.getInstance().hasCookies()); //Also prints false in 2.3 and true in 4.0.3
}
I'm testing the same code in two different devices and the funny thing is, the cookies are set (and also transferred between launches of the application) correctly in 4.0.3 but not in 2.3.3. When I say they are not set, I mean that hasCookies() returns false and also getCookie() returns null when I provide the URL.
I've tried every possible combination for the Cookie URL when calling setCookie: "http://alpha.mydomainname.com", "http://www.mydomainname.com", "http://mydomainname.com", "mydomainname.com", "alpha.mydomainname.com", ".mydomainname.com", "www.mydomainname.com", none of them works. Please help.
I recently had a similar problem, and the following solution worked for me. I create/get instances of CookieSyncManager and CookieManager at the beginning, and use them throughout the code, instead of creating new instances again. I also had to experiment with setting the cookie on the correct domain - I had to set it to the domain that appears in one of the redirects.
final CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context);
final CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
//Save the two cookies: auth token and session info
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
String cookieString = cookie.getName() + "=" + cookie.getValue() + "; Domain=" + cookie.getDomain();
cookieManager.setCookie("http://mydomainname.com", cookieString);
}
cookieSyncManager.sync();
}
I've faced the same problem. There is not so clear how to use the setCookie method. You should use it with some loop if you have a 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)
}
So you can't use it like:
CookieManager.getInstance().setCookie("http://someHost.com", "key1=someValue1;key2=someValue2;key3=someValue3")
I also ran into some strange behaviours with CookieManager, eventually I ended up with a solution that is a workaround - but it works.
Instead of using CookieManager I just used the http cookie headers, so for example using HttpUrlConnection it can look like that:
//Save the two cookies: auth token and session info
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
String cookieString = cookie.getName() + "=" + cookie.getValue();
myHttpURLConnection.setRequestProperty("Cookie", cookieString);
}
Of course, if you need to persist these cookies you will have to do it wourself and save their value somewhere for later use...
The cookie can't include the semicolon, because the semicolon means separator in cookies.

Categories

Resources