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_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response uploadFile(
@FormDataParam("file") InputStream aUploadedInputStream,
@FormDataParam("file") FormDataContentDisposition aFileDetail) {
UploadedFile uploadedFile = new UploadedFile();
uploadedFile.setOriginalFileName(aFileDetail.getFileName());
uploadedFile.setFileSize(aFileDetail.getSize());
saveToFile(aUploadedInputStream, aFileDetail.getType(), uploadedFile);
databaseHelper.saveInDatabase(uploadedFile);
return Response.status(200).build();
}
("UploadedFile" is an custom class to save the information of the file in a database)
And this is my client code:
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();
FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",
new File("C:/Users/Nicklas2751/Desktop/test.txt"), MediaType.APPLICATION_OCTET_STREAM_TYPE);
multiPart.bodyPart(fileDataBodyPart);
Response response = webTarget.request(
MediaType.MULTIPART_FORM_DATA).post(
Entity.entity(multiPart, multiPart.getMediaType()));
System.out.println(response.getStatus()+" "+response.getStatusInfo()+" "+response);
}
public static void main(String[] args) {
new Slimclient();
}
The server code runs without any problems but when i run the client i get the following error:
415 Unsupported Media Type InboundJaxrsResponse{ClientResponse{method=POST, uri=http://localhost:49158/rest/service/upload, status=415, reason=Unsupported Media Type}}
I searched the web for a good tutorial for jersey 2 and multipart fileupload but i can only find tutorials and examples for jersey 1 or with an HTML-Form as "Client". I hope sombody can help me :)