我有以下实现从表单身份验证获取令牌。

预期输出如下:

java - 如何在Java中获取 token-LMLPHP

但是,当我运行实现时,会得到如下结果。在响应对象中,看不到token。我不是Java方面的专家,我想知道我缺少什么。

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


这是源代码:

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());
}

最佳答案

调用EntityUtils#consume(HttpEntity)时,您将完全使用响应的内容并关闭基础流。但是,您实际上尚未将响应数据读入代码可访问的任何变量中,因此您不再有机会查看它。

而是,调用获取响应数据的方法之一。用于此的选项包括HttpEntity#getContent()以原始InputStream的形式访问响应主体,或EntityUtils#toString(HttpEntity, Charset)String的形式读取整个响应主体。 (在后一种情况下,请注意,如果响应正文很大,则以String的形式读取整个响应正文会影响您进程的内存占用。)调用其中任何一个之后,您可以将检索到的内容传递给您选择JSON解析器来检索"token"

完成所有操作后,调用EntityUtils#consume(HttpEntity)以保证清除由实体封装的任何基础资源(例如流)仍然是一个好习惯。

09-27 23:27