Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract httponly cookie from a post request in Java?

I have the following cURL request

curl -i --data 'user=user1&password=password1' -X POST http://127.0.0.1:8080/login

This returns me the following response:

    HTTP/1.1 200 OK
    Access-Control-Allow-Origin:
    Access-Control-Allow-Credentials: true
    Access-Control-Allow-Headers: authorization,Content-Type
    Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, HEAD, DELETE
    Date: Monday, January 22, 2017 10:07:22 AM UTC
    Set-Cookie: JSESSIONID=XXXYYYZZZ; Path=/; HttpOnly
    Content-Type: application/json
    Content-Length: 118
    Server: Jetty(9.2.15.v20160210)
    {"status":"OK","message":"","body":{"principal":"user1","ticket":"el23-esedejhz943"}}

I want to make this call in Java, and extract the JSESSIONID present in Set-Cookie field. How can I do this?

like image 788
Dan Avatar asked Jun 29 '26 21:06

Dan


1 Answers

a way to do it without using any external library, works for http, but not for https (because of certificates - this could be set up to work, but is too broad for this post)

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JsessionIdExtractor {

    public static void main(String[] args) throws Exception {
        String jSessionId = logInAndRetrieveJsessionId();
        System.out.println("JSESSIONID is: " + jSessionId);
    }

    private static String logInAndRetrieveJsessionId() throws Exception {
        String url = "http://127.0.0.1:8080/login";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Some browser name eg. fierfox");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        String postParameters = "user=user1&password=password1";
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postParameters);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + postParameters);
        System.out.println("Response Code : " + responseCode);
        return extractJsessionId(con);
    }

    private static String extractJsessionId(HttpURLConnection con) {
        Map<String, List<String>> headerFields = con.getHeaderFields();
        Set<String> headerFieldsSet = headerFields.keySet();
        Iterator<String> hearerFieldsIter = headerFieldsSet.iterator();
        while (hearerFieldsIter.hasNext()) {
            String headerFieldKey = hearerFieldsIter.next();
            if ("Set-Cookie".equalsIgnoreCase(headerFieldKey)) {
                List<String> headerFieldValue = headerFields.get(headerFieldKey);
                for (String headerValue : headerFieldValue) {
                    System.out.println("Cookie Found...");
                    String[] fields = headerValue.split(";\\s*");
                    String cookieValue = fields[0];
                    if (cookieValue.toUpperCase().trim().startsWith("JSESSIONID")) {
                        return cookieValue.split("=")[1];
                    }
                }
            }
        }
        throw new RuntimeException("there is no JSESSIONID cookie in reponse");
    }
}
like image 160
Krzysztof Cichocki Avatar answered Jul 01 '26 12:07

Krzysztof Cichocki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!