Java client for restful web service using Jersey API
In this page you will come to know how to create java client for restful web services using Jersey API. You will see
two sections here, the first section talks about how to connect to "GET" request, and the second section shows how to connect to "POST"
type of requests.
We are referring to the previous example as a restful web services.
Java Client for GET Request using Jersey API
package com.java2novice.rest.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JersyGetClient {
public static void main(String a[]){
String url = "http://localhost:8080/RestfulWebServices/order-inventory/order/1016";
Client restClient = Client.create();
WebResource webResource = restClient.resource(url);
ClientResponse resp = webResource.accept("application/json")
.get(ClientResponse.class);
if(resp.getStatus() != 200){
System.err.println("Unable to connect to the server");
}
String output = resp.getEntity(String.class);
System.out.println("response: "+output);
}
}
|
The output for above code is:
Output: |
response: {"custmer":"Java2Novice","address":"Bangalore","bill-amount":"$2000"}
|
Java Client for POST Request using Jersey API
In this example you will see how to send json input through java client using POST method:
package com.java2novice.rest.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyPostClient {
public static void main(String a[]){
String url = "http://localhost:8080/RestfulWebServices/order-inventory/order";
String jsonInput = "{\"custmer\":\"Java2novice\",\"address\":\"Bangalore\","+
"\"bill-amount\":\"$2000\"}";
Client restClient = Client.create();
WebResource webResource = restClient.resource(url);
ClientResponse resp = webResource.type("application/json")
.post(ClientResponse.class, jsonInput);
if(resp.getStatus() != 200){
System.err.println("Unable to connect to the server");
}
String output = resp.getEntity(String.class);
System.out.println("response: "+output);
}
}
|
The output for above code is:
Output: |
response: Your order is in-progress
|
|