2017-08-04 109 views
1

我有以下實現從表單身份驗證獲取令牌。如何在java中獲取令牌

預期輸出如下:

​​

然而,當我跑我的實現,我得到如下。在響應對象中,我沒有看到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()); 
} 

回答

2

當調用EntityUtils#consume(HttpEntity),你完全消耗響應的內容和關閉基礎流。但是,您實際上沒有將響應數據讀入您的代碼可訪問的任何變量中,因此您再也沒有機會查看它了。

相反,請調用其中一種獲取響應數據的方法。對此的選項包括HttpEntity#getContent()以訪問響應主體作爲原始InputStreamEntityUtils#toString(HttpEntity, Charset)以讀取整個響應主體爲String。 (在後一種情況下,請注意,如果響應主體很大,立即讀取整個響應主體爲String將影響進程的內存佔用量。)調用其中一個之後,可以通過JSON解析器傳遞檢索到的內容選擇檢索"token"

完成之後,調用EntityUtils#consume(HttpEntity)以保證清除由實體封裝的任何底層資源(如流)仍然是一個好習慣。