Java Rest

java

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?

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();
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License