Content-Length分隔邮件正文的过早结束(预期:

时间:2014-04-18 11:04:49

标签: java apache-httpclient-4.x

我试图在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)

我的代码是:

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);

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

2 个答案:

答案 0 :(得分:11)

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

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

答案 1 :(得分:6)

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

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

return downloadFile(httpEntity, targetDirectory, fileName);

在关闭客户端之前调整我的代码以下载文件之后,它现在正在为我工​​作。下面的代码类似于我现在所做的:

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