Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

java - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here enter image description here


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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...