RestEasy client framework file upload

让人想犯罪 __ 提交于 2019-12-02 23:21:26
Frank Rünagel

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!