HttpClient POST 请求 returns 状态 200 没有任何 body(但它应该是)。内容的长度是-1

HttpClient POST request returns status 200 without any body (however it should be). Length of the content is -1

我将 Apache HttpClient 用于 POST 对 Web 服务的请求。 我得到

httpResult=200

然而没有body。我知道一些 body 应该在那里 当我 使用另一个 POST 调用方法,然后我得到 JSON 格式的 body。

在此方法中,响应的长度 body = -1.

response.getEntity().getContentLength() = -1;

The result of EntityUtils.toString(response.getEntity()) is empty string.

密码是:

    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

     }

谁能给我一些解决问题的提示?

此外我想添加给我正确响应的代码body。在这种情况下,我使用 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 

            ...
        } 

请将 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.