Search code examples
javaresthttpclient

Upload file using java MultipartEntityBuilder throws Content too long. What's an alternative?


I'm trying to make a little utility that will synchronise data between two servers. Most of the calls there are REST calls with JSON, so I decided to use Apache HttpClient for this. There is however a section where I need to upload a file. I'm trying to do this using the mutipart form data with the MutipartEntityBuilder but I encounter a Content too long problem. (I tried to gzip the contents of the file too, but I'm still going over the limit).

Here's my java code:

        HttpPost request = new HttpPost(baseUrl+URL);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        //create upload file params
        builder.addTextBody("scanName", "Test upload");
        builder.addBinaryBody("myfile", f);

        HttpEntity params= builder.build();

        request.setEntity(params);

        request.addHeader("content-type","multipart/form-data");

        HttpResponse response = httpClient.execute(request);

Are there better atlernatives that I should be using for the file upload part? I'm also going to download the files from one of the server. Will I hit a similar issue when try to handle those responses?

Is there something I'm doing wrong?


Solution

  • I try to use your code and send some file with size something about 33MB and it was successful. So, I think your problem one of the follows:

    1. Created http client has limitations for request size - in this case you need to change properties of client or use another client;

    2. In some peace of code you call HttpEntity.getContent() method. For multipart request for this method exists limitations - 25kB. For this case you need to use writeTo(OutputStream) instead of getContent()

    In comments you told about swagger, but I don't understand what does it mean. If you use swagger generated api, that problems maybe occurred at their code and you need to fix generation logic (or something like this - I never used swagger)

    I hope my answer will help you