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:
- Capture the output in string format
- 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 !!
Hello Lokesh,
Could you please explain difference between rest and restful services and restful webservice
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
A similar code example is here: https://howtodoinjava.com/spring-boot/spring-boot-rest-controller-example/
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…
Copy the API for /users, Users.java in this code. It will work. Simpe copy and paste.
Can I have binary data as well in the User Bean like defining an Input Strteam object
Hi Lokesh,
After configuring the above code and jersey servlet in web.xml when I try to run I am getting 404 error. My path is http://localhost:8080/RestFul/rest/user-management/users/10
as my project name is RestFul and jersery url-pattern is /rest/*
Please let me know why am I getting the 404 error.
Can you please post the relevant xml configuration and code. Can’t figure out just like that.
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/*
Seems like some problem in posting xml on the screen, the above is the data of my web.xml…
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.
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)
You need to fake your “User-Agent” header.
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!
Good point. If jaxb is already with you, then you only need resteasy. RESTeasy is jboss provided and not in default java distribution. You will need it.
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!
RESTEasy is preconfigured and completely integrated with JBoss 6-M4 and higher. you can rely completely on JBoss for scanning for your JAX-RS services and deploying them. All you have to provide is your JAX-RS service classes packaged within a WAR either as POJOs, CDI beans, or EJBs and provide an empty web.xml file. https://docs.jboss.org/resteasy/2.0.0.GA/userguide/html/Installation_Configuration.html#d0e219
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!
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.