Search code examples
javaapache-httpclient-4.xhttp-proxyform-authentication

How to get token in java


I have the following implementation to get token from form authentication.

The expected output is as follows:

enter image description here

However, when I run my implementation, I am getting as follows. In the response object, I do not see token. I am not an expert on Java, I wonder what I am missing.

Login form get: HTTP/1.1 200 OK
response: HttpResponseProxy{HTTP/1.1 200 OK [Cache-Control: max-age=0, Content-Type: application/json, Date: Fri, 04 Aug 2017 21:05:04 GMT, transaction_id: 729097fd-69ac-b813-26c7-015daf10ddfd, X-Powered-By: Express, Content-Length: 684, Connection: keep-alive] ResponseEntityProxy{[Content-Type: application/json,Content-Length: 684,Chunked: false]}}
Post logon cookies:
None

Here is the source code:

BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCookieStore(cookieStore)
            .build();

HttpHost proxy = new HttpHost("xxx.xxx.xxx.com", 80, "http");
RequestConfig  config = RequestConfig.custom()
         .setProxy(proxy)
         .build();

HttpUriRequest login = RequestBuilder.post()
     .setUri(new URI("https://api.xxx.com:443/tokens"))
     .addParameter("username", "stackoverflow")
     .addParameter("password", "isbest!")
     .setConfig(config)
     .build();

CloseableHttpResponse response2 = httpclient.execute(login);
HttpEntity entity = response2.getEntity();
System.out.println("Login form get: " + response2.getStatusLine());

EntityUtils.consume(entity);
System.out.println("response: " + response2);

System.out.println("Post logon cookies:");
List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
    System.out.println("None");
} else {
    for (int i = 0; i < cookies.size(); i++) {
    System.out.println("- " + cookies.get(i).toString());
}

Solution

  • When you call EntityUtils#consume(HttpEntity), you are fully consuming the content of the response and closing the underlying stream. However, you haven't actually read the response data into any variable accessible by your code, so you no longer have any opportunity to look at it.

    Instead, call one of the methods that fetches the response data. Options for this include HttpEntity#getContent() to access the response body as a raw InputStream or EntityUtils#toString(HttpEntity, Charset) to read the whole response body as a String. (In the latter case, be aware that reading the whole response body at once as a String will impact your process's memory footprint if the response body is large.) After calling either one of those, you can pass the retrieved content through your JSON parser of choice to retrieve the "token".

    Once you're all done, it's still good practice to call EntityUtils#consume(HttpEntity) to guarantee cleanup of any underlying resources encapsulated by the entity, such as streams.