3

I'm trying, as a client, to post a zip file to a "Restservice", using RestEasy 3.0.19. This is the code:

public void postFileMethod(String URL)  {       
         Response response = null;              
         ResteasyClient client = new ResteasyClientBuilder().build();
         ResteasyWebTarget target = client.target(URL); 

         MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

         FileBody fileBody = new FileBody(new File("C:/sample/sample.zip"), 
ContentType.MULTIPART_FORM_DATA);              

         entityBuilder.addPart("my_file", fileBody);            
         response = target.request().post(Entity.entity(entityBuilder, 
MediaType.MULTIPART_FORM_DATA));            
}   

The error I get is this one:

javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request
....
Caused by: javax.ws.rs.ProcessingException: RESTEASY003215: could not 
find writer for content-type multipart/form-data type: 
org.apache.http.entity.mime.MultipartEntityBuilder

How can I solve this problem? I looked into some posts, but the code is slightly different from mine.

Thank you guys.

MDP
  • 4,177
  • 21
  • 63
  • 119

1 Answers1

2

You are mixing two different HTTP clients RESTEasy and Apache HttpClient. Here is the code which uses RESTEasy only

public void postFileMethod(String URL) throws FileNotFoundException {
    Response response = null;
    ResteasyClient client = new ResteasyClientBuilder().build();
    ResteasyWebTarget target = client.target(URL);

    MultipartFormDataOutput mdo = new MultipartFormDataOutput();
    mdo.addFormData("my_file", new FileInputStream(new File("C:/sample/sample.zip")), MediaType.APPLICATION_OCTET_STREAM_TYPE);
    GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(mdo) { };

    response = target.request().post(Entity.entity(entity,
            MediaType.MULTIPART_FORM_DATA));
}

You need to have resteasy-multipart-provider to have it working:

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-multipart-provider</artifactId>
    <version>${resteasy.version}</version>
</dependency>
Ilya
  • 2,177
  • 15
  • 19
  • My doubt is: I have to send a zip file, not using a form, but taking it programmaticaly from the client hard disk. Should I stil use "MultipartFormDataOutput" e "MediaType.MULTIPART_FORM_DATA"? – MDP Feb 08 '19 at 07:52
  • 1
    It depends on the server side implementation of the endpoint. If it's implemented using `multipart/form-data` then you must use `MediaType.MULTIPART_FORM_DATA`. More info [here](https://stackoverflow.com/questions/32336083/file-upload-api-multipart-form-data-vs-raw-contents-in-body) – Ilya Feb 08 '19 at 10:03