How to handle Cookies with Apache HttpClient 4.3

35,675

Your code looks OK to me (other than not releasing resources, but I presume exception handling was omitted for brevity). The reason for cookie store being empty may be violation of the actual cookie policy (which is BEST_MATCH in your case) by the target server. So, cookies sent by the server get rejected as invalid. You can find out if that is the case (and other useful contextual details) by turning on context / wire logging as described here

Share:
35,675
ali
Author by

ali

Updated on October 03, 2020

Comments

  • ali
    ali over 3 years

    I need to implement a series of HTTP requests in Java and decided to use Apaches HttpClient in version 4.3 (the most current one).

    The problem is all these requests use a cookie for session management and I seem to be unable to find a way of accessing that cookie and passing it from request to request. My commands in using curl look something like:

    # Login
    curl -c cookies -d "UserName=username&Password=password" "https://example.com/Login"
    
    # Upload a file
    curl -b cookies -F fileUpload=@IMG_0013.JPG "https://example.com/File"
    
    # Get results of server processing file
    curl -b cookies "https://example.com/File/1234/Content"
    

    They work perfectly. However with HttpClient it seems not to work. What I tried was:

        URI serverAddress = new URI("https://example.com/");
    
        URI loginUri = UriBuilder.fromUri(serverAddress).segment("Login").queryParam("UserName", "username")
                .queryParam("Password", "password").build();
    
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
        CookieStore cookieStore = new BasicCookieStore();
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);
    
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();
        HttpGet httpGet = new HttpGet(loginUri);
        CloseableHttpResponse loginResponse = httpClient.execute(httpGet,context);
    
        System.out.println(context.getCookieStore().getCookies());
    

    The output of the last line is always an empty list. I think it should contain my Cookie, am I right?

    Can someone give me a small example on how to handle the cookie using Apache HttpClient 4.3?

    Thanks