0
我使用Apache HttpClient進行Web服務的POST請求。 我越來越HttpClient POST請求返回狀態200沒有任何正文(但它應該是)。內容的長度是-1
httpResult = 200
但是沒有身體。我知道一些身體應該在當我 使用另一個POST調用方法,那麼我得到的身體在JSON格式。
在此方法中,響應body的長度= -1。
response.getEntity()。getContentLength() = -1;
EntityUtils.toString(response.getEntity())的結果爲空字符串。
的代碼是:
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
JSONObject attributes = new JSONObject();
JSONObject main = new JSONObject();
attributes.put("201", "Frank");
main.put("attributes", attributes);
main.put("primary", "2");
String json = main.toString();
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
httpResult = response.getStatusLine().getStatusCode();
client.close();
if (httpResult == HttpURLConnection.HTTP_OK) {
HttpEntity ent = response.getEntity();
Long length = ent.getContentLength();
System.out.println("Length: " + length);// length = -1
}
任何人都可以給我一些提示如何解決這個問題?
此外我想添加給我一個正確的響應正文的代碼。在這種情況下,我使用HttpURLConnection。
HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
urlConnect.setConnectTimeout(10000);
urlConnect.setRequestProperty("Accept", "application/json");
urlConnect.setRequestProperty("Content-Type", "application/json");
urlConnect.setRequestMethod("POST");
JSONObject attributes = new JSONObject();
JSONObject main = new JSONObject();
attributes.put("201", "Frank");
main.put("primary", "2");
main.put("attributes", attributes);
urlConnect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConnect.getOutputStream());
wr.write(main.toString());
wr.flush();
httpResult = urlConnect.getResponseCode();
System.out.println("Http Result: " + httpResult);
if (httpResult == HttpURLConnection.HTTP_OK) {
InputStream response = urlConnect.getInputStream(); // correct not empty response body
...
}
請告訴我的'EntityUtils.toString(response.getEntity())'結果? –
** EntityUtils.toString(response.getEntity())**的結果是空字符串。 –
你走了。沒有實體返回響應,所以長度爲-1。使用其他一些HTTP客戶端時能夠獲得響應嗎? –