Java Content-Length 分隔的消息正文过早结束(预期:

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23152816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:04:26  来源:igfitidea点击:

Premature end of Content-Length delimited message body (expected:

javaapache-httpclient-4.x

提问by Khanjee

I am trying to get HTTP response with the help of apache httpclient. I get headers successfully but it throws exception when I try to get contents. Exception is:

我试图在 apache httpclient 的帮助下获得 HTTP 响应。我成功获取标题,但是当我尝试获取内容时它抛出异常。例外是:

 org.apache.http.ConnectionClosedException: Premature end of Content-Length delimited message body (expected: 203856; received: 1070
        at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:180)
        at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
        at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
        at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
        at java.io.InputStreamReader.read(InputStreamReader.java:184)
        at java.io.BufferedReader.fill(BufferedReader.java:154)
        at java.io.BufferedReader.readLine(BufferedReader.java:317)
        at java.io.BufferedReader.readLine(BufferedReader.java:382)

and my code is:

我的代码是:

InputStream is = entity.getContent();
BufferedReader br = new BufferedReader( new InputStreamReader(is, "UTF-8"));
String line;
String str = "";
while ((line = br.readLine()) != null) {

    str = str + line + "\n";

}
log.debug(str);

any help will be appreciated. thanks

任何帮助将不胜感激。谢谢

采纳答案by Daniel Renshaw

The problem appears to be on the server-side, not in the client code you've pasted.

问题似乎出在服务器端,而不是您粘贴的客户端代码中。

The server claimed that the content contained 203856 bytes but only sent 1070.

服务器声称该内容包含 203856 个字节,但仅发送了 1070 个。

回答by Nitin

I might be replying on it late. But I also encounter the same problem. And I got the resolution of it. In my case I was closing the client before utilizing the HttpEntity. And after closing the client I was trying to download the file. Below code is similar to what I was doing:

我可能回复晚了。但我也遇到同样的问题。我得到了它的解决方案。就我而言,我在使用 HttpEntity 之前关闭了客户端。关闭客户端后,我试图下载文件。下面的代码与我正在做的类似:

HttpEntity httpEntity = null;
try (final CloseableHttpClient client = createHttpClient()) {
     httpEntity = getEntity(client);
}

return downloadFile(httpEntity, targetDirectory, fileName);

After adjusting my code to download the file before closing the client, Its working now for me. Below code is similar to what I did now:

在关闭客户端之前调整我的代码以下载文件后,它现在对我有用。下面的代码类似于我现在所做的:

try (final CloseableHttpClient client = createHttpClient()) {
     HttpEntity httpEntity = getEntity(client);
     return downloadFile(httpEntity, targetDirectory, fileName);
}