Core Java

JAX-RS Client Example

1. Introduction

In this article we are going to present an example code of writing a JAX-RS Client. As the reader would be aware JAX-RS API is a standard to simplify the writing of RESTful Web Services and their clients in Java. This will be a Jersey Client and we will assume that we have a Server already set-up that would intercept and respond to the requests fired from our Client. The entire code is available for download at the end of the article.

2. Project Set-Up

We will set-up a Maven project from the Eclipse IDE. Steps are as shown in the screenshots below.

  • Start-up Eclipse and then go to File->New->Project…
  • From the wizard that comes up choose the creation of a Maven project and then click Next
  • The next wizard screen should be as shown below. Note how we have selected the creation of a simple project.

    Fig.1 Choose the creation of a simple Maven project
    Fig.1 Choose the creation of a simple Maven project
  • In the following wizard screen just fill in the details as shown here and then click Finish.

    Fig.2 Fill in the artifactId and groupId
    Fig.2 Fill in the artifactId and groupId
  • Finally we will have the following project structure
    Fig. 3 Final project structure
    Fig. 3 Final project structure
  • Create an appropriately named package inside src/main/java, add jaxRSClientExample.java class to it and we are good to go

3. Add Maven Dependency

We will use the latest version 1.19 of Jersey. Add the Maven dependency for Jersey-client in the pom.xml file

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javacodegeeks.example</groupId>
  <artifactId>JaxRSClient</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
  	<jersey.version>1.19</jersey.version>
  </properties>
  <dependencies>
  	<dependency>
  		<groupId<com.sun.jersey</groupId>
  		<artifactId<jersey-client</artifactId>
  		<version<${jersey.version}</version>
  	</dependency>
  </dependencies>
</project>

4. Write Client Code

As stated above it is assumed that we have a Server up and running. In the below section we are going to write Client code to make a get and post request to it in jaxRSClientExample.java.

  • First, create a ‘Client’ instance
  • From the Client instance, obtain an instance of a WebResource. It is used for building requests and sending it to the Web Resource and then processing the response obtained.
  • Next, we create a ClientResponse object which will hold the response obtained from the Web Resource

4.1 GET Request

The following code demonstrates a GET request

getRequest

package com.javacodegeeks.rest.jersey.client;

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

public class jaxRSClientExample {

	Client client = Client.create();'
        //set the appropriate URL
	String getUrl = "http://localhost:8080/JAXRS-JSON/rest/student/data/get";
		
       public static void main(){
           getRequest();
       }        

       public static void getRequest(){
		WebResource webResource = client.resource(getUrl);
		ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
		//a successful response returns 200
                if(response.getStatus()!=200){
			throw new RuntimeException("HTTP Error: "+ response.getStatus());
		}
		
		String result = response.getEntity(String.class);
		System.out.println("Response from the Server: ");
		System.out.println(result);
	}

4.2 POST Request

The following code snippet demonstrates a POST request. Notice that we are posting a JSON object to the server.

postRequest

package com.javacodegeeks.rest.jersey.client;

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

public class jaxRSClientExample {

	Client client = Client.create();
	//Set the appropriate URL for POST request
	String postUrl = "http://localhost:8080/JAXRS-JSON/rest/student/data/post";

	public static void postRequest(){
	  WebResource webResource = client.resource(postUrl);
	  String inputData = "{\"firstName\":\"Alice\",\"lastName\":\"Brown\",\"school\":\"Bright Stars\",\"standard\":\"Three\",\"rollNumber\":1212}";
	  ClientResponse response = webResource.type("application/json").post(ClientResponse.class,inputData);
		if(response.getStatus()!=201){
			throw new RuntimeException("HTTP Error: "+ response.getStatus());
		}
		
	   String result = response.getEntity(String.class);
	   System.out.println("Response from the Server: ");
	   System.out.println(result);
	}

      public static void main(){
           postRequest();
       } 

5. Outputs

Bring up the server and then fire the requests from the client. And one should see the outputs printed on the console.

5.1 Output from GET Request

Response from the Server:
{"firstName":"Elizabeth","lastName":"Hayden","school":"Little Flower","standard":"One","rollNumber":1113}

5.2 Output from POST Request

Response from the Server:
Record entered: Alice Brown is a student of standard Three at Bright Stars

6. Download the Eclipse Project

This brings us to the end of this article. Hope it was an interesting and rewarding read.

Download
You can download the full source code of this example here : JaxRSClient

Joormana Brahma

She has done her graduation in Computer Science and Technology from Guwahati, Assam. She is currently working in a small IT Company as a Software Engineer in Hyderabad, India. She is a member of the Architecture team that is involved in development and quite a bit of R&D. She considers learning and sharing what has been learnt to be a rewarding experience.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button