我有以下实现来从表单身份验证中获取令牌。
预期输出如下:
然而,当我运行我的实现时,我得到如下。在响应对象中,我没有看到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());
}
答案 0 :(得分:2)
当您致电EntityUtils#consume(HttpEntity)
时,您将完全消耗响应内容并关闭基础流。但是,您实际上没有将响应数据读入代码可访问的任何变量中,因此您不再有机会查看它。
相反,请调用其中一个获取响应数据的方法。此选项包括HttpEntity#getContent()
以原始InputStream
或EntityUtils#toString(HttpEntity, Charset)
的形式访问回复正文,以将整个回复正文作为String
读取。 (在后一种情况下,请注意,如果响应主体很大,立即读取整个响应主体将String
将影响进程的内存占用。)在调用其中任何一个之后,您可以传递检索到的内容通过您选择的JSON解析器来检索"token"
。
完成所有操作后,调用EntityUtils#consume(HttpEntity)
以保证清理实体封装的任何底层资源(例如流)仍然是一种好习惯。