java.net.cookiehandler

Query in java.net.cookiehandler

One of the features of java CookieHandler in java.net.cookiehandler is that one can only get access to their code by logging in their URL using the following. 

CookieHandler.setDefault(new CookieManager);

This function is very suitable and stable but there is a thing that keeps on bugging the minds of the programmers. The question is how java maintains cookies between each new HttpsURLConnection. 

The code to explain the above query is given below: 

public class GmailApp {

    private List<String> cookies;
    private HttpsURLConnection conn;

    public static void main(String[] args) throws Exception {

        String url = "https://accounts.google.com/ServiceLoginAuth";
        String gmail = "https://mail.google.com/mail/";

        GmailApp http = new GmailApp();

        // CookieHandler.setDefault(new CookieManager());

        String page = http.GetPageContent(url);
        String postParams = http.getFormParams(page, "myemail@gmail.com", "mypassword");
        http.sendPost(url, postParams);

        String result = http.GetPageContent(gmail);
        System.out.println(result);
    }

    private void sendPost(String url, String postParams) throws Exception {

        URL obj = new URL(url);
        conn = (HttpsURLConnection) obj.openConnection();
        conn.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + postParams);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in =
                new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    }

    private String GetPageContent(String url) throws Exception {

        URL obj = new URL(url);
        conn = (HttpsURLConnection) obj.openConnection();
        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        if (cookies != null) {
            for (String cookie : this.cookies) {
                conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
            }
        }
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in =
                new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        setCookies(conn.getHeaderFields().get("Set-Cookie"));
        return response.toString();
    }

    public String getFormParams(String html, String username, String password)
            throws UnsupportedEncodingException {

        System.out.println("Extracting form's data...");

        Document doc = Jsoup.parse(html);

        Element loginform = doc.getElementById("gaia_loginform");
        Elements inputElements = loginform.getElementsByTag("input");
        List<String> paramList = new ArrayList<String>();
        for (Element inputElement : inputElements) {
            String key = inputElement.attr("name");
            String value = inputElement.attr("value");

            if (key.equals("Email"))
                value = username;
            else if (key.equals("Passwd"))
                value = password;
            paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
        }

        StringBuilder result = new StringBuilder();
        for (String param : paramList) {
            if (result.length() == 0) {
                result.append(param);
            } else {
                result.append("&" + param);
            }
        }
        return result.toString();
    }

    public void setCookies(List<String> cookies) {
        this.cookies = cookies;
    }

}

One can use this code to login into their Gmail account without even using CookieHandler.setDefault(new CookieManager);

 

 

Processing 

When using java.net to statically set a default CookieHandler. Current and future HttpURLConnections (via their underlying HTTP client classes) will check for the existence of this default cookie handler and, if found, use it to retrieve cookies for requests and store newly set or returned cookies. This is done by calling CookieHandler.setDefault(). For as long as you wish to preserve cookies across all requests, this offers a static cookie-jar. Make that the CookiePolicy, or Java.net, is set as intended. The default setting for CookiePolicy is ACCEPT ORIGINAL SERVER.

Apart from that, there are a few errors in the above code as well. 

cookie.split(";", 1)[0]

 

The problem here is that this divide is useless; one wants a cookie. If the user wants to truncate the string after the first semicolon, they can use split(“;”, 2)[0] (1->2).

Additionally, the user only calls setCookies after your GET requests; hence, one must additionally collect the cookies in the POST login response.

 

 

Also Read: Prediction using Lasso and Ridge Regression

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *