Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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:

 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 + "
";

}
log.debug(str);

any help will be appreciated. thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...