简体   繁体   中英

RESTeasy client code for attaching a file

I need to attach a file to my service end-point . I tested the functionality via POSTMAN ( chrome browser plugin to test rest service ) , it is working fine.

But I need to test the same with JUNIT . For that case I am using RESTeasy client .

I was trying with this code :

    StringBuilder sb = new StringBuilder();

    BufferedReader br = new BufferedReader(new FileReader("C:/Temp/tempfile.txt"));
    try {
        String line = br.readLine();
        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
    }
    finally {
        br.close();
    }

    byte[] file = sb.toString().getBytes();

Client client = ClientBuilder.newClient();
        Invocation.Builder builder = client.target(webTarget.getUri()
                + "/attachment" ).request(MediaType.MULTIPART_FORM_DATA_TYPE);

        Response response = builder.post(Entity.entity(file, MediaType.MULTIPART_FORM_DATA), Response.class);

But I am getting an error :

org.apache.commons.fileupload.FileUploadException : the request was rejected because no multipart boundary was found

Is there any solution for this ?

Or can anybody give a sample RESTeasy rest client code to attach a file ?

Multipart has a special format. If the server is expecting a multipart/form-data format, we can't just send it as a normal request. You can look at the preview window in Postman to see the format

在此输入图像描述在此输入图像描述


You can see that each part has a boundary. We don't really have to worry about setting this manually. Resteasy has an API for building multiform output. You can use the MultipartFormDataOutput class to build the output. Just use the addFormData method to add parts. In your case its only one part, but the request will still get formatted the way the server is expecting.

So your request should look something more like

MultipartFormDataOutput output = new MultipartFormDataOutput();
                      // file (below) doesn't have to be a `byte[]`
                      // It can be a `File` object and work just the same
output.addFormData("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE);

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

This is assuming you have the required dependency, as I imaging you would, if the server is accepting multipart

<dependency>
   <groupId>org.jboss.resteasy</groupId>
   <artifactId>resteasy-multipart-provider</artifactId>
   <version>${resteasy.version}</version>
</dependency>


And just for completeness...

For any future readers who are curious about server side (since you haven't provided your code), this is what I used to test

@Path("/multipart")
public class MultipartResource {

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response postData(MultipartFormDataInput input) throws Exception {

        byte[] bytes = input.getFormDataPart("file", byte[].class, null);
        JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bytes)));

        return Response.ok("GOT IT").build();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM