3

I'm using Java with HttpAsyncClient, and trying to make a post request to a server using multipart/form. There are two parameters: one is just a string, while the second one is a fie/byte array. When I need to perform requests with large size byte arrays, I get the following exception: org.apache.http.ContentTooLongException: Content length is too long.

Is there any way to overcome this issue? How could I make a large sized request with multipart/form using Java and this entity?

Here is some of my code:

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

Where rawContent is just a byte array.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
baki1995
  • 83
  • 2
  • 9
  • Solution here: https://stackoverflow.com/questions/42763042/upload-file-with-multipart-post-request-using-apache-http-async-client – Raipe May 26 '21 at 06:46

1 Answers1

-1

Answer to this question 'Is there any way to overcome this issue? ' : you can try this code in your 'MultipartFormEntity' class

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

 }
Anshul Sharma
  • 3,432
  • 1
  • 12
  • 17
  • 4
    MultipartFormEntity is not my class, its an apache class used with Http Client. I'm pretty sure this code you just posted is already present there. – baki1995 Aug 17 '17 at 06:11