Search code examples
androidcookieswebviewhttpclient

Android sync cookies webview and httpclient


I have a login webview and httpclient that need to confirm if the user is logged in. The problem is that the webview and the httpclient are using other cookies so the httpclient can't get the webview cookies.

I read a lot of people questions and tutorials, but nothing worked. some of the things I read:

I read few other tutorials on Android Development and other websites but nothing worked.

another post: https://stackoverflow.com/questions/28052461/syncing-webview-with-httpclient

The problem is that the cookies won't sync.

something I tried:

        WebView webview;
        webview = (WebView) rootView.findViewById(R.id.webview);

        webview.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                CookieSyncManager.getInstance().sync();

            }
        });
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setUseWideViewPort(true);
        webview.setWebChromeClient(new WebChromeClient());
        webview.loadUrl("http://www.klh-dev.com/lehava/lehava/system/mlogin.php");

and some more:

   public String IsLoggedIn() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpClient client=new DefaultHttpClient();



                    HttpGet get=new HttpGet(url);
                     ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    try {
                        response_str=client.execute(get,responseHandler);
                        System.out.println(response_str);
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    Cookie sessionInfo;
                    List<Cookie> cookies = client.getCookieStore().getCookies();

                    if (! cookies.isEmpty()){
                            CookieSyncManager.createInstance(getApplicationContext());
                            CookieManager cookieManager = CookieManager.getInstance();

                            for(Cookie cookie : cookies){
                                    sessionInfo = cookie;
                                    String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue() + "; domain=" + sessionInfo.getDomain();
                                    cookieManager.setCookie(URLn, cookieString);
                                    CookieSyncManager.getInstance().sync();
                            }
                    }
                }
            }).start();
            return response_str;
   }

*The httpget return 1 or 0

I want to take cookies from webview and use them in my httpclient request

EDIT (added darpan's answer):

    public static BasicCookieStore getCookieStore(String cookies, String domain) {
        String[] cookieValues = cookies.split(";");
        BasicCookieStore cs = new BasicCookieStore();

        BasicClientCookie cookie;
        for (int i = 0; i < cookieValues.length; i++) {
            String[] split = cookieValues[i].split("=");
            if (split.length == 2)
                cookie = new BasicClientCookie(split[0], split[1]);
            else
                cookie = new BasicClientCookie(split[0], null);

            cookie.setDomain(domain);
            cs.addCookie(cookie);
        }
        return cs;

        }

    public String IsLoggedIn() {
        new Thread(new Runnable() {
            @Override
            public void run() {




                     String cookies = CookieManager.getInstance().getCookie("http://klh-dev.com/lehava/lehava/system/isloggedin.php");
                     BasicCookieStore lCS = getCookieStore(cookies, "klh-dev.com");

                     HttpContext localContext = new BasicHttpContext();
                     DefaultHttpClient httpclient = new DefaultHttpClient();
                     httpclient.setCookieStore(lCS);
                     localContext.setAttribute(ClientContext.COOKIE_STORE, lCS);

                HttpGet get=new HttpGet("http://klh-dev.com/lehava/lehava/system/isloggedin.php");
                 ResponseHandler<String> responseHandler = new BasicResponseHandler();



                try {
                    result=httpclient.execute(get,localContext);
                    response_str = EntityUtils.toString(result.getEntity());
                    System.out.println(response_str);
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }).start();
        return response_str;
    }
}

EDIT2: Finally works!! This is my code:

public static String IsLoggedIn() {
    new Thread(new Runnable() {
        @Override
        public void run() {
                 String cookies = CookieManager.getInstance().getCookie(getUrl);
                 BasicCookieStore lCS = getCookieStore(cookies, "klh-dev.com");

                 HttpContext localContext = new BasicHttpContext();
                 DefaultHttpClient httpclient = new DefaultHttpClient();
                 httpclient.setCookieStore(lCS);
                 localContext.setAttribute(ClientContext.COOKIE_STORE, lCS);

            HttpGet get = new HttpGet("http://klh-dev.com/lehava/lehava/system/isloggedin.php");


            try {
                result=httpclient.execute(get,localContext);
                response_str = EntityUtils.toString(result.getEntity());
                System.out.println(response_str);
                ((MainActivity) getContext).UpdateMenu();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }).start();
    return response_str;
}

and about the getUrl variable. I had to set a global variable like this:

private static String getUrl;

public String getUrl() {
    return getUrl;
}  

On every fragment I had to add onPageFinished: getUrl = view.getUrl();

Thank you.


Solution

  • In your code, you seem to be doing opposite of what you wish to do (Get cookie from Webview and set in HttpClient)

    Edit: From Mor Haviv's answer -

    You need to Define a global variable that stores current url in the view -

    private static String getUrl;
    

    Getting cookie from webview -

    @Override
    public void onPageFinished(WebView view, String url){
        getUrl = view.getUrl();
        String cookies = CookieManager.getInstance().getCookie(getUrl);
        Log.d(TAG, "All the cookies in a string:" + cookies);
    }
    

    Reference for above code

    Set this string named 'cookies' in your HttpClient -

    public static BasicCookieStore getCookieStore(String cookies, String domain) {
    String[] cookieValues = cookies.split(";");
    BasicCookieStore cs = new BasicCookieStore();
    
    BasicClientCookie cookie;
    for (int i = 0; i < cookieValues.length; i++) {
        String[] split = cookieValues[i].split("=");
        if (split.length == 2)
            cookie = new BasicClientCookie(split[0], split[1]);
        else
            cookie = new BasicClientCookie(split[0], null);
    
        cookie.setDomain(domain);
        cs.addCookie(cookie);
    }
    return cs;
    
    }
     //And, use the same 'getUrl' here to fetch the cookie. (Haviv's addition)
     String cookies = CookieManager.getInstance().getCookie(getUrl);
     BasicCookieStore lCS = getCookieStore(cookies, YOUR_APP_DOMAIN);
    
     HttpContext localContext = new BasicHttpContext();
     DefaultHttpClient httpclient = new DefaultHttpClient();
     httpclient.setCookieStore(lCS);
     localContext.setAttribute(ClientContext.COOKIE_STORE, lCS);
    

    PS - Put your app's domain at 'YOUR_APP_DOMAIN' And, I couldn't check the code as I don't have your domain.

    Reference for above code