I want to write a simple jersey 2 client to upload a file. I\'m using Jersey 2.10.1 and wrote following server code:
@POST
@Consumes(MediaType.MULTIPART_FORM
I've found my problem. I've missed to set the MediaType
of the MultiPart
and with the .request(MediaType.MULTIPART_FORM_DATA)
I've set the expected MediaType
of the response to MULTIPART_FORM_DATA
. Here is the working code:
public class Slimclient {
private static final String TARGET_URL = "http://localhost:49158/rest/service/upload";
public Slimclient() {
Client client = ClientBuilder.newBuilder()
.register(MultiPartFeature.class).build();
WebTarget webTarget = client.target(TARGET_URL);
MultiPart multiPart = new MultiPart();
multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",
new File("C:/Users/Nicklas/Desktop/aab.txt"),
MediaType.APPLICATION_OCTET_STREAM_TYPE);
multiPart.bodyPart(fileDataBodyPart);
Response response = webTarget.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(multiPart, multiPart.getMediaType()));
System.out.println(response.getStatus() + " "
+ response.getStatusInfo() + " " + response);
}
public static void main(String[] args) {
new Slimclient();
}
}