RestEasy client framework file upload

2019-03-12 20:40发布

Does anyone know how to create the RestEasy client side calls to upload a file using the following two interface signatures? I'm not finding any information at all. I know how to do it using the HttpClient but I'd like to use the client proxy to keep it consistent.

@POST
@Path("/upload")
@Consumes("multipart/form-data")
public void uploadFile(MultipartFormDataInput input);

@POST
@Path("/upload2")
@Consumes("multipart/form-data")
public void uploadFile2(@MultipartForm FileUploadForm form);

Any help would be appreciated, Fredrik

2条回答
男人必须洒脱
2楼-- · 2019-03-12 21:29

With RESTEasy 3.0.X a file upload via MultipartFormData could look like this:

ResteasyClient client = new ResteasyClientBuilder().build();

ResteasyWebTarget target = client.target("http://.../upload");

MultipartFormDataOutput mdo = new MultipartFormDataOutput();
mdo.addFormData("file", new FileInputStream(new File("....thermo.wav")),
    MediaType.APPLICATION_OCTET_STREAM_TYPE);
GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(mdo) {};

Response r = target.request().post( Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE));
查看更多
唯我独甜
3楼-- · 2019-03-12 21:31

I spent a bunch of time looking around for an answer to this, but I finally figured out how to make it work. You need to add:

resteasy-multipart-provider-2.3.5.Final.jar 

to your classpath (or whatever version of resteasy you are using). You then can do something of this form:

ClientRequest add_request = request();

MultipartFormDataOutput upload = new MultipartFormDataOutput();
upload.addFormData("data", recording, MediaType.APPLICATION_XML_TYPE);
upload.addFormData("file", Resources.toByteArray(Resources.getResource("thermo.wav")), MediaType.APPLICATION_OCTET_STREAM_TYPE);

add_request.body(MediaType.MULTIPART_FORM_DATA_TYPE, upload);

ClientResponse<?> recording_response = add_request.post();
Assert.assertEquals(Response.Status.CREATED, recording_response.getResponseStatus());

The last line is just a JUnit test assertion; it is not needed. thermo.wav is specified by @FormParam("file") and is loaded here into a byte array using Google Guava's Resources class. You can create the byte array however you want.

查看更多
登录 后发表回答