user
user

Reputation: 65

sync cookies between webview and java

I am almost dead doing this.Need help.

My Requirement :-

I am developing an android app and want to use the cookies(/session) from webview in my java code. I basically want to get the html of other pages of an url after login in webview without opening those pages in webview but through my java code.

What I tried :-

For this I tried HttpClient and HttpURLConnection referring many SO questions but failed.

Can anybody please give me a sample code?

Say I have cookies in a hashmap cookies. How Can I use HttpClient and HttpURLConnection or anything else to get the other page html. The website I am trying with is https:

Please give a sample code

Upvotes: 0

Views: 2021

Answers (2)

iAmLearning
iAmLearning

Reputation: 1174

If I am right u are trying to use your webview's cookies to get other pages of site in your activity java code.if yes try this:

BufferedReader reader = null;
try {
    URL url2 = new URL("url");
    URLConnection con = (URLConnection) url2.openConnection();
    CookieManager.getInstance().setAcceptCookie(true);

    con.setRequestProperty("Cookie",CookieManager.getInstance().getCookie("logged in url in webview"));
    con.setDoOutput(true);
    con.connect();

    reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    StringBiffer html;
    String line = "";
    while ((line = reader.readLine()) != null) {
        html.append(line);
    }
} catch (Exception e) {
    e.printStackTrace();
}  

It worked for me.

Upvotes: 2

Kiril Aleksandrov
Kiril Aleksandrov

Reputation: 2591

Have you tried to add the cookie as a HTTP header? I am not sure if I have understood you right but you can consider these:

  • Cookies: If you want to load some resource (no matter if it is a web page, image, css, js or something else) you are making a HTTP request. If the server keeps a session for your user, you are probably given a session cookie. The cookie must be sent with each request to the server as e COOKIE header. So if you want to pass the cookie to your request, add it as a header. Android provides you an easy way to do this with the CookieManager class. You can refer to this.
  • SSL: If you are trying to access a secured web site (https) you have to use an SSL certificate. Android comes up with a bunch of predistributed certificates for most of the popular web cites (e.g Facebook, Google, Twitter, etc.). You can use them out of the box. If your SSL certificate is not presented, you have to add it manually. Read this for more information.

I hope this was useful :)

Upvotes: 1

Related Questions