Writing a Native Java REST Client

So far in this blog, we have been learning about building RESTful webservices which are server side components. In this post, we will learn to build a RESTful client for consuming the webservices written in previous posts.

I will be re-using the code base written for RESTEasy + JAXB xml example. I will build a pure java API client without using any third party tools.

1) Build the RESTful webservice API

Follow the steps given in RESTEasy + JAXB xml example

For reference, service and model classes are:


package com.howtodoinjava.service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import com.howtodoinjava.model.User;

public class UserManagementModule
	public Response getUserById(@PathParam("id") Integer id)
		User user = new User();
		return Response.status(200).entity(user).build();


package com.howtodoinjava.model;
import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "user")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @XmlAttribute(name = "id")
    private int id;
    @XmlElement(name = "firstName")
    private String firstName;
    @XmlElement(name = "lastName")
    private String lastName;
    public int getId() {
        return id;
    public void setId(int id) {
        this.id = id;
    public String getFirstName() {
        return firstName;
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    public String getLastName() {
        return lastName;
    public void setLastName(String lastName) {
        this.lastName = lastName;

2) Create the RESTFul webservices consumer client

Our java client is based on java.net package APIs. I am doing two steps here:

  1. Capture the output in string format
  2. Unmarshal the model object from xml response

package test;

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

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.howtodoinjava.model.User;

public class PureJavaClient 
	public static void main(String[] args) 
			URL url = new URL("http://localhost:8080/RESTfulDemoApplication/user-management/users/10");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("Accept", "application/xml");

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

			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
			String apiOutput = br.readLine();

			JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));

		} catch (MalformedURLException e) {
		} catch (IOException e) {
		} catch (JAXBException e) {


<?xml version="1.0" encoding="UTF-8" standalone="yes"?><user id="10"><firstName>Lokesh</firstName><lastName>Gupta</lastName></user>

Follow the below link for downloading the source code of this example.

Source code download

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

19 thoughts on “Writing a Native Java REST Client”

  1. I have a requirement like there is no particular user and I need the list of all users and my url will be like /users instead of /users/{id} which is used for a particular user. with /users I need to get the list of all users, please let me know how this can be achieved with the same user pojo and needs to send the data in xml format only

  2. Hi Lokesh,
    I am using your Client to receive a XML file and parse it via REST Webservice. I replaced the URL URL url = new URL(“http://localhost:8080/RESTfulDemoApplication/user-management/users/10”) with my new URL which is htttps.
    It connected fine but there are some extra characters in the output causing javax.xml.bind.UnmarshalException
    – with linked exception:
    [org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.]

    The output has 

    My XML on the browser shows as

    Thanks for your help.

  3. Hi I am getting an exception when i tried to invoke a rest service through this approach , can you please help me.

    java.io.FileNotFoundException: http://localhost:8080/RestServiceExample/api/Services/getMsgFrUser?userName=Pavan
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1675)
    at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1673)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1671)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1244)
    at com.javamad.rest.RestClient.main(RestClient.java:33)
    Caused by: java.io.FileNotFoundException: http://localhost:8080/RestServiceExample/api/Services/getMsgFrUser?userName=Pavan
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1624)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
    at com.javamad.rest.RestClient.main(RestClient.java:31)

  4. Thanks Lokesh for your quick response. I was wondering since I will be planning on using java.net package for HTTP connection, sending requests and receiving response and also since JAXBContext API is included with JAVA , do we still need to download RESTEasy and jaxb jars manually?


      • Hello Lokesh,

        We are actually using JBoss 6 and not 7. I was wondering if we need to have the RESTeasy jars for jboss in order to implement Restful client in java using HHTPURLConnection?
        We do have the jaxb jars that comes with java.
        Our requirement is not very complex , just need to send some data and get a response back . Also, I was planning to use the XML format for data exchange as jaxB will help to marshall/unmarshall the data..


  5. Nice tutorial . I just had one question… Our application runs on JBoss 7 , jdk 1.6 and IDE used is Eclipse Juno. Currently we do not have the maven project or maven installed with our eclipse.

    In order to consume third party Restful webservices , other than creating a Client class to call the the URL (as shown in the example above in PureJavaClient Class) and annotating the model class in order to unmarshall the response received back from server, Do I still need to set up maven project or anything on the server side ?
    We do not have to produce/provide websrvices at this point of time..


    • Maven absolutely not needed. It is just for dependency management i.e. it will download all jars for you, just tell it which module you want. So, if you are not using maven, you need to manually download the required jars i.e. RESTEasy and jaxb.


Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.