WebServices- JAX-RS RESTFul Java Clinets

JAX-RS RESTFul Java Clinets

So far we used URL directly to Test our RESTful service. But in the real time we will call the services by writing some client application logic. We have different ways to write a RESTful client

They are

  • java.net.URL

  • Apache HttpClient

  • RESTEasy client

  • Jersey client

Every Java Clinet can send two types of requests

  1. GET

  2. POST

We will see one by one by Example. Here we are Taking JAXRS-JSON-Jersey-Example for writing clinets. For all webservices are same. Only difference in Java Clinets

JAXRS-JSON-Jersey-Example

1.Create Dynamic web project in eclipse, convert that into Maven Project

2.Configure pom.xml, web.xml (May change for Every Java Clinet, please Observe)

3.Craete UserBo for Converting Java Object to JSON data

package rest.service;

public class UserBo {

	String username;
	String password;

	public String getUsername() {
 return username;
	}

	public void setUsername(String username) {
 this.username = username;
	}

	public String getPassword() {
 return password;
	}

	public void setPassword(String password) {
 this.password = password;
	}

	@Override
	public String toString() {
 return "USER [username=" + username + ", password=" + password + "]";
	}

}

4.Create Web Service having both @GET @POST for testing with Java Clinets

package rest.service;

import javax.ws.rs.core.Response;

@Path("/json")
public class JSONService {
	@GET
	@Path("/getjson")
	@Produces(MediaType.APPLICATION_JSON)
	public UserBo getboInJSON() {

 UserBo bo = new UserBo();
 bo.setUsername("satyakaveti@gmail.com");
 bo.setPassword("XCersxg34CXeWER341DS@#we");
 return bo;
	}
	
	@POST
	@Path("/postjson")
	@Consumes(MediaType.APPLICATION_JSON)
	public Response createTrackInJSON(UserBo bo) {

 String result = "USER DATA SAVED!! " + bo;
 return Response.status(201).entity(result).build();

	}

}

5.Test Webservice directly by using URL / writing webservice client

GET: http://localhost:8080/JAXRS-JSON-JavaClients-Example/rest/json/getjson

POST: http://localhost:8080/JAXRS-JSON-JavaClients-Example/rest/json/postjson

So far we are used above process to Test the Web Services. Now lets see how to test webservices with Java clinets.

1.java.net.URL

Here we will use -java.net.URL” and -java.net.HttpURLConnection” to create a simple Java client to send -GET” and -POST” request.

GET Request Example

package rest.clients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetUrlGETClient {

	public static void main(String[] args) {

 try {

	URL url = new URL("http://localhost:8080/JAXRS-JSON-JavaClients-Example/rest/json/getjson");
 	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 	conn.setRequestMethod("GET");
 	conn.setRequestProperty("Accept", "application/json");

 	if (conn.getResponseCode() != 200) {
 throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
 	}

 	BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

 	String output;
 	System.out.println("Output from Server .... \n");
 	while ((output = br.readLine()) != null) {
  System.out.println(output);
 	}

 	conn.disconnect();

 } catch (MalformedURLException e) {

 	e.printStackTrace();

 } catch (IOException e) {

 	e.printStackTrace();

 }

	}
}

POST Request Example

package rest.clients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetUrlPOSTClient {
	public static void main(String[] args) {

 try {

	URL url = new URL("http://localhost:8080/JAXRS-JSON-JavaClients-Example/rest/json/postjson");
 	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 	conn.setDoOutput(true);
 	conn.setRequestMethod("POST");
 	conn.setRequestProperty("Content-Type", "application/json");

String input = "{\"username\":\"satyakaveti@gmail.com\",\"password\":\"XCersxg34CXeWER341DS@#we\"}";

 	OutputStream os = conn.getOutputStream();
 	os.write(input.getBytes());
 	os.flush();

 	if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
 throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
 	}

 	BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

 	String output;
 	System.out.println("Output from Server .... \n");
 	while ((output = br.readLine()) != null) {
  System.out.println(output);
 	}

 	conn.disconnect();

 } catch (MalformedURLException e) {
 	e.printStackTrace();
 } catch (IOException e) {
 	e.printStackTrace();
 }

	}
}

2.Apache HttpClient

Apache HttpClient is available in Maven central repository, just declares it in your Maven pom.xml file.

1. Configure POM.xml with Apache HTTPClinet

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.1.1</version>
</dependency>

2.GET Request Example

package rest.clients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class ApacheHttpClientGet {

	public static void main(String[] args) {
 try {

 	DefaultHttpClient httpClient = new DefaultHttpClient();
 	HttpGet getRequest = new HttpGet("http://localhost:8080/JAXRS-JSON-JavaClients-Example/rest/json/getjson");
 	getRequest.addHeader("accept", "application/json");
 	HttpResponse response = httpClient.execute(getRequest);

 	if (response.getStatusLine().getStatusCode() != 200) {
  throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
 	}

 	BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

 	String output;
 	System.out.println("Output from Server .... \n");
 	while ((output = br.readLine()) != null) {
  System.out.println(output);
 	}

 	httpClient.getConnectionManager().shutdown();

 }  catch (Exception e) {
 	e.printStackTrace();
 	}
 }
}

3.POST Request Example

package rest.clients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class ApacheHttpClientPost {

	public static void main(String[] args) {

 try {

 	DefaultHttpClient httpClient = new DefaultHttpClient();
 	HttpPost postRequest = new HttpPost("http://localhost:8080/JAXRS-JSON-JavaClients-Example/rest/json/postjson");

 	StringEntity input = new StringEntity("{\"username\":\"satyakaveti@gmail.com\",\"password\":\"XCersxg34CXeWER341DS@#we\"}");
 	input.setContentType("application/json");
 	postRequest.setEntity(input);

 	HttpResponse response = httpClient.execute(postRequest);

 	if (response.getStatusLine().getStatusCode() != 201) {
  throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
 	}

 	BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

 	String output;
 	System.out.println("Output from Server .... \n");
 	while ((output = br.readLine()) != null) {
  System.out.println(output);
 	}

 	httpClient.getConnectionManager().shutdown();

 } catch (MalformedURLException e) {

 	e.printStackTrace();

 } catch (IOException e) {

 	e.printStackTrace();

 }

	}

}

3.RESTEasy client

1. Configure POM.xml with
RESTEasy client framework is included in RESTEasy core module, so, you just need to declares the -resteasy-jaxrs.jar” in your pom.xml file

<dependency>
	<groupId>org.jboss.resteasy</groupId>
	<artifactId>resteasy-jaxrs</artifactId>
	<version>2.2.1.GA</version>
</dependency>

2.GET Request Example

package rest.clients;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class RESTEasyClientGet {

	public static void main(String[] args) {
	  try {

 ClientRequest request = new ClientRequest(
  "http://localhost:8080/JAXRS-JSON-JavaClients-Example/rest/json/getjson");
 request.accept("application/json");
 ClientResponse<String> response = request.get(String.class);

 if (response.getStatus() != 200) {
 	throw new RuntimeException("Failed : HTTP error code : "
  + response.getStatus());
 }

 BufferedReader br = new BufferedReader(new InputStreamReader(
 	new ByteArrayInputStream(response.getEntity().getBytes())));

 String output;
 System.out.println("Output from Server .... \n");
 while ((output = br.readLine()) != null) {
 	System.out.println(output);
 }

	  } catch (ClientProtocolException e) {
 e.printStackTrace();
	  } catch (IOException e) {
 e.printStackTrace();
	  } catch (Exception e) {
 e.printStackTrace();
	  }
	}
}

3.POST Request Example

package rest.clients;

import java.io.InputStreamReader;
import java.net.MalformedURLException;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;

public class RESTEasyClientPost {

	public static void main(String[] args) {

	  try {

 ClientRequest request = new ClientRequest(
 	"http://localhost:8080/JAXRS-JSON-JavaClients-Example/rest/json/postjson");
 request.accept("application/json");

 String input = "{\"username\":\"satyakaveti@gmail.com\",\"password\":\"XCersxg34CXeWER341DS@#we\"}";
 request.body("application/json", input);

 ClientResponse<String> response = request.post(String.class);

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

 BufferedReader br = new BufferedReader(new InputStreamReader(
 	new ByteArrayInputStream(response.getEntity().getBytes())));

 String output;
 System.out.println("Output from Server .... \n");
 while ((output = br.readLine()) != null) {
 	System.out.println(output);
 }

	  } catch (MalformedURLException e) {
 e.printStackTrace();
	  } catch (IOException e) {
 e.printStackTrace();
	  } catch (Exception e) {
 e.printStackTrace();
	  }
	}
}

4. Jersey client

1. Configure POM.xml with
To use Jersey client APIs, declares -jersey-client.jar” in your pom.xml file.

<dependency>
	<groupId>com.sun.jersey</groupId>
	<artifactId>jersey-client</artifactId>
	<version>1.8</version>
</dependency>

2.GET Request Example

package rest.clients;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientGet {

	public static void main(String[] args) {
 try {

 	Client client = Client.create();

 	WebResource webResource = client
  	.resource("http://localhost:8080/JAXRS-JSON-JavaClients-Example/rest/json/getjson");

 	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);

 	System.out.println("Output from Server .... \n");
 	System.out.println(output);

 } catch (Exception e) {

 	e.printStackTrace();

 }

	}
}
Output
-------------------------------------
Output from Server .... 
{"username":"satyakaveti@gmail.com","password":"XCersxg34CXeWER341DS@#we"}

3.POST Request Example

package rest.clients;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

	public static void main(String[] args) {

 try {

 	Client client = Client.create();

 	WebResource webResource = client
  	.resource("http://localhost:8080/JAXRS-JSON-JavaClients-Example/rest/json/postjson");

 	String input = "{\"username\":\"satyakaveti@gmail.com\",\"password\":\"XCersxg34CXeWER341DS@#we\"}";

 	ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);

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

 	System.out.println("Output from Server .... \n");
 	String output = response.getEntity(String.class);
 	System.out.println(output);

 } catch (Exception e) {
 	e.printStackTrace();
 }
	}
}
Output
----------------------------------
Output from Server .... 
USER DATA SAVED!! USER [username=satyakaveti@gmail.com, password=XCersxg34CXeWER341DS@#we]