HttpClient POST请求返回状态200而没有任何正文(但它应该是)。内容的长度为-1

时间:2017-05-03 16:15:27

标签: java post apache-httpclient-4.x

我使用Apache HttpClient对Web服务进行POST请求。 我正在

  

httpResult = 200

然而,没有身体。我知道有些身体应该在那里作为当我 使用另一种POST调用方法,然后我将以JSON格式获取正文。

在此方法中,响应体的长度= -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 

            ...
        } 

1 个答案:

答案 0 :(得分:1)

请将client.close();移至最后,即处理完回复后。

要从HttpUrlConnection中提取回复,请使用以下

InputStream response = urlConnect.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(response));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
    sb.append(line+"\n");
}
br.close();

JSONObject object = new JSONObject(sb.toString()); //Converted to JSON Object from JSON string - Assuming response is a valid JSON object.