【问题标题】:MultipartFormEntity - Content too longMultipartFormEntity - 内容太长
【发布时间】:2018-01-25 09:53:00
【问题描述】:

我将 Java 与 HttpAsyncClient 一起使用,并尝试使用 multipart/form 向服务器发出 post 请求。有两个参数:一个只是一个字符串,而第二个是一个文件/字节数组。当我需要执行大尺寸字节数组的请求时,我得到以下异常: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 只是一个字节数组。

【问题讨论】:

标签: java http multipart apache-httpcomponents apache-httpasyncclient


【解决方案1】:

回答这个问题'有什么办法可以克服这个问题吗? ' : 您可以在“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);
     }

 }

【讨论】:

  • MultipartFormEntity 不是我的类,它是一个与 Http Client 一起使用的 apache 类。我很确定您刚刚发布的这段代码已经存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2022-01-17
  • 2017-12-04
  • 1970-01-01
  • 2018-05-19
相关资源
最近更新 更多