How To: Using Jersey Client to Upload in Java

Ajax and especially jQuery make HTTP requests very simple when you’re writing javascript. But what if you need to make a request in Java? Jersey is great for writing the backend of your jax-rs service and it turns out it makes writing a client simple too. Here are a few common requests and how to make them:

Multipart Form Data

final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); WebTarget target = client.target("http://localhost:8080/resource/mydoc"); final FileDataBodyPart filePart = new FileDataBodyPart("file", new File("C:/mydoc.pdf")); FormDataMultiPart formDataMultiPart = new FormDataMultiPart(); final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart.field("foo", "bar").bodyPart(filePart); final Response response = target.request().post(Entity.entity(multipart, multipart.getMediaType())); // do something with the response System.out.println(response); formDataMultiPart.close(); multipart.close();

File Upload

final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); WebTarget target = client.target("http://localhost:8080/resource/mydoc"); final File fileToUpload = new File("C:/mydoc.pdf"); final Response response = target.request().put(Entity.entity(new FileInputStream(fileToUpload), new MediaType("application", "pdf"))); // do something with the response System.out.println(response);

POST data

final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); WebTarget target = client.target("http://localhost:8080/resource/mydoc"); Response response = target.request().post(Entity.json(myJson)); // do something with the response System.out.println(response);

Basic Authentication

HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("username", "password"); final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); client.register(feature);