Java Rest

java

https://eclipse-ee4j.github.io/jersey.github.io/documentation/latest/user-guide.html

client.setConnectTimeout(900000);
client.setReadTimeout(900000);

How can we make a GET REST call using Jersey?

Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/RESTfulExample/rest/json/metallica/get");
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
if (response.getStatus() != 200) {
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);

The above code use jersey-client-1.8.jar and jersey-core-1.8.jar

How can we make a POST REST call using Jersey?

Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/RESTfulExample/rest/json/metallica/post");
String input = "{\"singer\":\"Metallica\",\"title\":\"Fade To Black\"}";
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);

if (response.getStatus() != 201) {
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);

The above code use jersey-client-1.8.jar and jersey-core-1.8.jar

How can we make a request with specific request headers?

First example:

Client client = Client.create();
WebResource resource = client.resource(serviceEndPoint);
WebResource.Builder builder = resource.accept(MediaType.APPLICATION_JSON);
builder.type(MediaType.APPLICATION_JSON);
builder.header("Content-Type", "application/json");

ClientResponse response = builder.post(ClientResponse.class, json.toString());
String responseBody = response.getEntity(String.class);
int status = response.getStatus();
Second example:

package com.example.jersey.rest.api;

import java.io.File;
import java.nio.file.Paths;
import java.util.Map;

import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.glassfish.jersey.media.multipart.ContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;

import jersey.repackaged.com.google.common.collect.Maps;

public class JerseyClientPost  {
    private static final String UAT_URL = "SOME URL REST END POINT";
    private final static String USERNAME = "...";
    private final static String PWD = "...";

    public JerseyClientPost() throws Exception {

        HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(USERNAME, PWD);
        Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
        client.register(feature);
        WebTarget webTarget = client.target(UAT_URL);

        FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",  Paths.get("C:/US24188/sample.xml").toFile());
        fileDataBodyPart.setMediaType(MediaType.APPLICATION_XML_TYPE);

        ContentDisposition cd = fileDataBodyPart.getContentDisposition();        
        fileDataBodyPart.getHeaders().add("Content-Length", cd.getSize() + "");
        fileDataBodyPart.getHeaders().add("Content-Disposition","form-data; name=\"file\"; filename=\"sample.xml\"");

        final Map<String, String> parameters = Maps.newHashMap();
        parameters.put("boundary", "oUenkuwN4QC3NNxsILTJq7FEsL905dy3M");

        FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
        formDataMultiPart.setMediaType(new MediaType("multipart", "form-data", parameters).withCharset("UTF-8"));
        formDataMultiPart.bodyPart(fileDataBodyPart);

        System.out.println(formDataMultiPart.getMediaType());

        Response response = webTarget.request()
                .header("Accept", "text/plain, */*")
                .header("User-Agent", "Java/1.8.0_241")
                .header("Content-Type", "multipart/form-data;charset=UTF-8;boundary=oUenkuwN4QC3NNxsILTJq7FEsL905dy3M")
                 .post(Entity.entity(formDataMultiPart, formDataMultiPart.getMediaType()), Response.class);

        System.out.println(response.getStatus() + " --> "    + response.getStatusInfo() + " --> " + response);
    }

    public static void main(String[] args) throws Exception {
        new JerseyClientPost();
    }
}

In the above (second) example, I've put the code that make the REST request in the constructor. In general, putting expensive code such as making a rest request or a database request inside a constructor is consider a bad practice, so don't do that. Just use the above example as an example. In the above (second) example, I was making a REST request to a remote end point that I don't have control over. When I use Spring Boot, it worked fine with the remote end point, but it failed when we use Jersey. It seems that the remote end point was a bit dump. I had to use Fiddler to capture the traffic from both Spring Boot, and Jersey, and compare the raw data that were being sent. It seems that the Content-Disposition header created by Jersey for the file contains the time that the file was last modified, and the size of the file. The Content-Disposition header generated by Jersey seems to be correct, and the Content-Disposition header generated by Spring Boot seems to be correct as well, but they are a bit different. I did not want to modify how Jersey generate this header, but fortunately, by specifically adding the Content-Disposition header, it seems to prevent Jersey from generating that header, and it works.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License