Cookie setcookie is not reflecting - android

I am trying to set cookie using API CookieManager in webview for sencha page.
CookieSyncManager.createInstance(this);
cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(domain, cookie);
But session is not reflecting when page is loading in webview.

This is a working bit of code.
private void setCookie(DefaultHttpClient httpClient, String url) {
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
if (cookies != null) {
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
String cookieString = cookie.getName() + "=" + cookie.getValue();
cookieManager.setCookie(url, cookieString);
}
CookieSyncManager.getInstance().sync();
}
}
Here the httpclient is the DefaultHttpClient object you used in the HttpGet/HttpPost request. Also one thing to make sure is the cookie name and value, it should be given
String cookieString = cookie.getName() + "=" + cookie.getValue();
setCookie will the set the cookie for the given URL.

Related

Inject Cookies into a WebView

I am calling a service to get Cookies as a JSONArray that looks like this
{"domain":"blabla.com","expirationDate":1896127200,"hostOnly":false,"httpOnly":false,"name":"__ssid","path":"\/","sameSite":"no_restriction","secure":false,"session":false,"storeId":"0","value":"392997aa-ce67-4d96-a73d-de0ad794f7bf","id":1}
then parsing these cookies like this
Cookie cookie = new Cookie.Builder()
.domain(checkDomain(jsonObject.optString("domain")))
.expiresAt(jsonObject.optLong("expirationDate"))
.name(jsonObject.optString("name"))
.path(jsonObject.optString("path"))
.value(jsonObject.optString("value"))
.build();
then injecting the cookies like this
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.setAcceptThirdPartyCookies(webView, true);
} else {
cookieManager.setAcceptCookie(true);
}
cookieManager.removeAllCookie();
if (cookies != null) {
for (Cookie cookie : cookies) {
String cookieString = cookie.name() + "=" + cookie.value() + "; domain=" + cookie.domain();
cookieManager.setCookie(cookie.domain(), cookieString);
CookieSyncManager.getInstance().sync();
}
}
but when i load https://blabla.com into the WebView cookies are not working, am i missing anything?
Please help
This is what I worked with, it works perfectly fine:
CookieManager.getInstance().setCookie(treeUrl, cookieString);
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
webView.loadUrl("www.example.com");
If you have to inject a JSON to cookies, just use yourJson.toString()
You can use the below code to set cookies.
web_view = findViewById(R.id.web_view);
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(web_view.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie(URL,"uniqueId=10028; Domain=.codean.app");
cookieSyncManager.sync();
String cookie = cookieManager.getCookie(URL);
Log.e(TAG, ""+cookie);
web_view.getSettings().setJavaScriptEnabled(true);
web_view.setWebViewClient(new WebViewClient());
web_view.loadUrl(URL);
Output:
2019-09-16 15:20:21.412 31408-31408/com.sam.webviewtest E/MainActivity: uniqueId=10028
2019-09-16 15:20:22.204 31408-31408/com.sam.webviewtest E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-09-16 15:20:22.205 31408-31408/com.sam.webviewtest E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
For testing purpose, you can use below url
https://codean.app/so/cookies.php
in this php file, it only output all the cookies
<pre><?php print_r( $_COOKIE ); ?></pre>
I've used the same url in my above example,
Please try this one:
private fun setCookie(){
val cookieManager = CookieManager.getInstance()
cookieManager.acceptCookie()
val domain = "https://www.yourdomain.com"
webView.webViewClient = WebViewClient()
webViewTest.settings.javaScriptEnabled = true
webViewTest.loadUrl(domain)
cookieManager.setCookie(domain,"$cookieKey=$cookieValue")
cookieManager.setAcceptThirdPartyCookies(view.webViewTest,true)
}

Passing cookies in webview android

I have build an application to load WebView with passing cookies.my application works fine in KitKat version of android.
but WebView is not loading in jelly bean or lower versions. that means my WebView is not passing cookies in jelly bean or lower versions.
Is this possible not to load WebView in lower android versions? If possible, then how to do it?
please guide me and help me.
Hear i store cookie in my activity.
CookieSyncManager.getInstance().startSync();
CookieSyncManager syncManager = CookieSyncManager.createInstance(MainActivity2.this);
syncManager.sync();
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
cookies1 = cookieJar.getCookies();
editor.putString("coockies", String.valueOf(cookies1));
//List<Cookie> cookies = httpclient.getCookieStore().getCookies();
for (int i = 0; i < cookies1.size(); i++) {
cookie = cookies1.get(i);
Log.d("cookie", String.valueOf(cookie));
}
and hear i pass cookie in webview
enter code here wv = new WebView(this);
wv=(WebView)findViewById(R.id.webView);
HttpCookie sessionCookie = myactivity.cookie;
Log.d("Session Coockies",String.valueOf(sessionCookie));
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
if (sessionCookie != null) {
cookieManager.removeSessionCookie();
String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
Log.d("cookistring",cookieString);
cookieManager.setCookie("", cookieString);
CookieSyncManager.getInstance().sync();
// String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + ";domain=";
}
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setDomStorageEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//setContentView(myWebView);
String url="my url";
Log.d("url",url);
wv.loadUrl(url);

How to set cookie in Android WebView

I am facing issues with setting cookie in Android WebView. I am using the following code:
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(url, cookie);
CookieSyncManager.getInstance().sync();
But it's not working. I also tried by adding headers using WebView's loadUrl(String url, Map<String, String> additionalHttpHeaders) method; but still it's not working. Is there a way to do this?
Please try this
Cookie sessionCookie = LoginWebView.cookie;
CookieSyncManager.createInstance(webview.this);
CookieManager cookieManager = CookieManager.getInstance();
if (sessionCookie != null) {
cookieManager.removeSessionCookie();
String cookieString = sessionCookie.getName();
Log.v(TAG, "sync cookies: " + cookieString);
cookieManager.setCookie(domain, cookieString);
CookieSyncManager.getInstance().sync();
}
The CookieSyncManager is deprecated now, instead use cookieManager.flush(); to update.
See this: http://developer.android.com/intl/es/reference/android/webkit/CookieSyncManager.html

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.

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