3

我将 Java 与 HttpAsyncClient 一起使用,并尝试使用 multipart/form 向服务器发出发布请求。有两个参数:一个只是一个字符串,而第二个是一个文件/字节数组。当我需要执行大尺寸字节数组的请求时,我得到以下异常:org.apache.http.ContentTooLongException: Content length is too long。

有没有办法克服这个问题?如何使用 Java 和此实体通过 multipart/form 发出大型请求?

这是我的一些代码:

final HttpPost post = new HttpPost(uri);
final HttpEntity entity = MultipartEntityBuilder.create()
                .addTextBody("name", fileName).addBinaryBody("file", rawContent, ContentType.APPLICATION_OCTET_STREAM, fileName)
                .build();
post.setEntity(entity);
return client.execute(post, null);

rawContent 只是一个字节数组。

4

1 回答 1

0

回答这个问题'有什么办法可以克服这个问题吗?' :您可以在“MultipartFormEntity”类中尝试此代码

@Override
     public InputStream getContent() throws IOException {
         if (this.contentLength < 0) {
            throw new ContentTooLongException("Content length is unknown");
        } else if (this.contentLength > 25 * 1024) {
             throw new ContentTooLongException("Content length is too long: " + this.contentLength);
        }
         final ByteArrayOutputStream outstream = new ByteArrayOutputStream();
         writeTo(outstream);
         outstream.flush();
         return new ByteArrayInputStream(outstream.toByteArray());
     }

     @Override
     public void writeTo(final OutputStream outstream) throws IOException {
         this.multipart.writeTo(outstream);
     }

 }
于 2017-08-17T06:05:15.393 回答