RESTful webservices client using java.net package

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:

UserManagementModule.java

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;

@Path("/user-management")
public class UserManagementModule
{
	@GET
	@Path("/users/{id}")
	@Produces("application/xml")
	public Response getUserById(@PathParam("id") Integer id)
	{
		User user = new User();
		user.setId(id);
		user.setFirstName("Lokesh");
		user.setLastName("Gupta");
		return Response.status(200).entity(user).build();
	}
}

User.java

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;
 
@XmlAccessorType(XmlAccessType.NONE)
@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) 
	{
		try 
		{
			URL url = new URL("http://localhost:8080/RESTfulDemoApplication/user-management/users/10");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			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();
			System.out.println(apiOutput);
			conn.disconnect();

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

			System.out.println(user.getId());
			System.out.println(user.getFirstName());
			System.out.println(user.getLastName());
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
}

Output:

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

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

Source code download

Happy Learning !!

18 thoughts on “RESTful webservices client using java.net package”

  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

      1. Thanks Lokesh. The example uses spring framework. Cant we do that without spring as we did the above program because I like to do that using a stand alone program which sends only Response object as output…

      1. My web.xml is below:

        RestFul

        index.html
        index.htm
        index.jsp
        default.html
        default.htm
        default.jsp

        Jersey REST Service
        com.sun.jersey.spi.container.servlet.ServletContainer

        com.sun.jersey.config.property.packages
        com.rs.service

        1

        Jersey REST Service
        /rest/*

  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.

    404
    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?

    Thanks!

      1. 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..

        Thanks!

  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..

    Thanks!

    1. 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.

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Want to ask any question? Or suggest anything?