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();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…