marți, 6 octombrie 2015

JAX-RS consume a RESTful web service from a Servlet (including asynchronous)

In this post, you can see a simple example of consuming a RESTful web service from a Servlet (including asynchronous calls).

JavaEE 7 Client API for JAX-RS API is useful to access the RESTful web services. Basic steps:
  • Get the instance of class (entry point for invoking RESTful web services).
  • Create an instance of using the instance of Client class (used to invoke a RESTful web service at some location or URI).
  • Populate the target with the required data (e.g. MIME type, post data, query parameters), and create a request of appropriate HTTP method type which would be an instance of
  • Obtain the response from the desired RESTful web service via object.
Let's suppose that we have the following JAX-RS resource:

public class HelloWorldResource {

    @Produces("text/plain") // default: */*
    public String helloWorld() {
        return "Hello, World!";
Configured as:

public class ApplicationConfig extends Application {
If the application is named JaxrsSimpleServletClient_EE7, then the resource is available at:


From a Servlet we can access this resource like below:
public class ClientServlet extends HttpServlet {

    // for simple demo, URL is hard-coded
    private final String jaxrsResource = "http://localhost:8080/JaxrsSimpleServletClient_EE7/webresources/helloworld/";

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // get the instance of client which will be entry point to invoking services
        Client jaxrsClient = ClientBuilder.newClient();

        // targeting the JAX-RS serivce we want to invoke by capturing it in WebTarget instance
        WebTarget webTarget =;

        // build the request (e.g. a GET request)
        Invocation invocation = webTarget.request("text/plain").buildGet();

        // invoke the request
        Response jaxrsResponse = invocation.invoke();

        // respond to client (user)
        String hello = jaxrsResponse.readEntity(String.class);

        PrintWriter out = response.getWriter();
        out.println("<h3>" + hello + "</h3>");

    public String getServletInfo() {
        return "Client Server";

If you need to perform asynchronous request then add client support for making asynchronous calls to the server by using the AsyncContext class:
@WebServlet(urlPatterns={"/ClientServlet"}, asyncSupported=true)

Complete example is available here.

Read also:
Consume a RESTful web service from JSF

Niciun comentariu:

Trimiteți un comentariu