1

I have searched through a lot of answers and implemented one which helped me with maintaining cookies in volley request.

Code which helped me is following

CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

That code has helped me maintain same session with all volley request.

Right after this code I open a webview in onCreate method. Webview has different session and not shared with volley request.

How can I make sure that both has same session.

Following is my onCreate method

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    webView = findViewById(R.id.webview);
    /* Dialog view */
    LinearLayout linearLayoutProgressBar = findViewById(R.id.linearLayoutProgressBar);
    // Creates instance of the manager.

    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setSaveFormData(true);
    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

    WebViewClientImpl webViewClient = new WebViewClientImpl(this, linearLayoutProgressBar);
    webView.setWebViewClient(webViewClient);

    webAppInterface = new WebAppInterface(this, webView);
    webView.addJavascriptInterface(webAppInterface, "Android");

    webView.loadUrl(AppConstants.mobileUrl);

    //GetLocation function fetches the location and sends it to server.
    //So first webview is opened and then data is sent to server.
    getLocation();
}

Thank you

Mike Ross
  • 2,942
  • 5
  • 49
  • 101

2 Answers2

1

Another solution is to use CookieManager. The issue is that there are many CoockieManager depending on the context used. With Volley it is java.net.CookieManager and with WebView it is android.webkit.CookieManager. Both are not compatible with each other. The solution I found here is to create your own CookieManager extended from java.net.CookieManager. The goal is to send the request to the android.webkit.CookieManagerin the same time. Like this, both are synchronized.

Juste create the following class as is :

public class WebkitCookieManagerProxy extends CookieManager
{
    private android.webkit.CookieManager webkitCookieManager;

    public WebkitCookieManagerProxy()
    {
        this(null, null);
    }

    public WebkitCookieManagerProxy(CookieStore store, CookiePolicy cookiePolicy)
    {
        super(null, cookiePolicy);
        this.webkitCookieManager = android.webkit.CookieManager.getInstance();
    }

    @Override
    public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException
    {
        // make sure our args are valid
        if ((uri == null) || (responseHeaders == null)) return;
        // save our url once
        String url = uri.toString();
        // go over the headers
        for (String headerKey : responseHeaders.keySet())
        {
            // ignore headers which aren't cookie related
            if ((headerKey == null) || !(headerKey.equalsIgnoreCase("Set-Cookie2") || headerKey.equalsIgnoreCase("Set-Cookie"))) continue;
            // process each of the headers
            for (String headerValue : responseHeaders.get(headerKey))
            {
                this.webkitCookieManager.setCookie(url, headerValue);
            }
        }
    }

    @Override
    public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException
    {
        // make sure our args are valid
        if ((uri == null) || (requestHeaders == null)) throw new IllegalArgumentException("Argument is null");
        // save our url once
        String url = uri.toString();
        // prepare our response
        Map<String, List<String>> res = new java.util.HashMap<String, List<String>>();
        // get the cookie
        String cookie = this.webkitCookieManager.getCookie(url);
        // return it
        if (cookie != null) res.put("Cookie", Arrays.asList(cookie));
        return res;
    }

    @Override
    public CookieStore getCookieStore()
    {
        // we don't want anyone to work with this cookie store directly
        throw new UnsupportedOperationException();
    }
}

And finally, call once only, early in your code and before any https request :

WebkitCookieManagerProxy coreCookieManager = new WebkitCookieManagerProxy(null, java.net.CookiePolicy.ACCEPT_ALL);
java.net.CookieHandler.setDefault(coreCookieManager);

After looking for a solution for a long time, I found it here: Two way sync for cookies between HttpURLConnection (java.net.CookieManager) and WebView (android.webkit.CookieManager)

General Grievance
  • 4,555
  • 31
  • 31
  • 45
gduh
  • 1,079
  • 12
  • 30
0

From Volley Request, you have to take a cookie and store in shared preference.

then you can set the same cookie with your web view settings.

To retrieve cookie details from volley refer this link

To set the cookie to web view URL like

CookieManager cookieManager = CookieManager.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    cookieManager.setAcceptThirdPartyCookies(webView, true);
} else {
    cookieManager.setAcceptCookie(true);
}
cookieManager.setCookie(url, ${cookie});
webView.load(url);
  • I open the website first in WebView and then send volley request. Can I get cookie from webview and set it to volley or do I have to send volley request to server first, set cookie and then open webview url? – Mike Ross Jun 22 '20 at 07:19
  • You can get all cookies from current url by this way from web view Client `@Override public void onPageFinished(WebView view, String url){ String cookies = CookieManager.getInstance().getCookie(url); }` – Quintiple Team Jun 22 '20 at 09:33