5

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.

7
  • Please I still need help Commented Jan 20, 2015 at 18:07
  • You want cookies from webview and want to use them in your httpclient request? Commented Jan 21, 2015 at 14:53
  • A remote change - try adding .klh-dev.com at BasicCookieStore lCS = getCookieStore(cookies, "klh-dev.com"); If doesn't work, I am investigating the issue. Commented Feb 2, 2015 at 14:00
  • @darpan your answered helped me very much and it worked. I will tell you in a comment what did I do and edit you answer. I will do it soon Commented Feb 2, 2015 at 16:02
  • 1
    @Darpan I added my solution to the question. Just edit your answer or update it and I will approve it :) Commented Feb 3, 2015 at 12:44

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

I tried your answer, but I didn't success to insert the code. I did success to get the cookie from the webview (and I even saw it in the logs) but the to set the cookie string I failed. No matter where I put it, if I modify it (I did import all the things needed) or create a separate function for this operation its says syntax error. I edited the question and added what I tried.
Updated again, please check it out now and see why isn't it working properly. thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.