该问题似乎只发生在我尝试发布的“大”文件中。
我的代码如下所示:
PostMethod method = new PostMethod(url);
File input = new File(filePathname);
RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
method.setRequestEntity(entity);
method.setRequestHeader("Content-Disposition", "attachment; filename=xyzzy")
HttpClient client = new HttpClient();
Credentials defaultcreds = new UsernamePasswordCredentials("userid", "pw");
client.getState().setCredentials(new AuthScope("hostname", port, AuthScope.ANY_REALM), defaultcreds);
try {
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
throw new Exception("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
return new String(responseBody);
}
catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
throw e;
}
catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
throw e;
}
finally {
// Release the connection.
method.releaseConnection();
}
异常文本如下所示:
Fatal transport error: chunked stream ended unexpectedly Exception in thread "main" java.io.IOException: chunked stream ended unexpectedly at org.apache.commons.httpclient.ChunkedInputStream.getChunkSizeFromInputStream(ChunkedInputStream.java:252) at org.apache.commons.httpclient.ChunkedInputStream.nextChunk(ChunkedInputStream.java:221) at org.apache.commons.httpclient.ChunkedInputStream.read(ChunkedInputStream.java:176) at java.io.FilterInputStream.read(FilterInputStream.java:127) at org.apache.commons.httpclient.AutoCloseInputStream.read(AutoCloseInputStream.java:108) at java.io.FilterInputStream.read(FilterInputStream.java:101) at org.apache.commons.httpclient.AutoCloseInputStream.read(AutoCloseInputStream.java:127) at org.apache.commons.httpclient.HttpMethodBase.getResponseBody(HttpMethodBase.java:690)
无论我使用 getResponseBody() 还是 getResponseBodyAsStream(),我都会遇到类似的异常。
我不应该得到太多数据,但我发布了超过 200mb 的数据。
最佳答案
我可以通过更改 PostMethod 的 requestHeader 中指定的文件名值的长度来解决此问题。我一直在请求 header 中包含完整文件路径名的编码版本。通过反复试验,我发现我“发布”的文件的成功或失败似乎取决于它所在的文件夹。长文件夹文件路径名不起作用,而短文件夹文件路径名则不起作用,尽管具有相同的文件。因此,我从请求 header 中删除了路径名,只开始包含文件名,并且我不再看到问题。
关于java - 为什么当我使用 HttpClient 时,分块流会意外结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15076601/