Using javax.xml.ws.Dispatch for REST Client

The JAX-WS has a javax.xml.ws.Dispatch class that you can use for making HTTP call, So i can use it even for making call to REST service and i wanted to see how that works. I do have a Contact REST service that allows me to make CRUD calls on the Contact table, For example i can call http://localhost:9080/MyWebService/rest/contact/1 URL to get a record from CONTACT table where contact Id is 1. This is the output i get when i call it for contactId 1
The REST service returns CONTACT object in XML format for contactId equal to 1, I wanted to try making the same call using the javax.xml.ws.Dispatch object, this is the code that i built for it.

package com.webspherenotes.rest;

import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.http.HTTPBinding;

public class DispatcherTest1 {

  public static void main(String[] args) {
    QName serviceName = new QName("http://www.webspherenotes.com/rest", "svc");
      QName portName = new QName("http://www.webspherenotes.com/rest", "port");
      Service svc = Service.create(serviceName);
      svc.addPort(portName, HTTPBinding.HTTP_BINDING,
   "http://localhost:9080/MyWebService/rest/contact/1");
      Dispatch dis =
        svc.createDispatch(portName, Source.class, Service.Mode.PAYLOAD);
      Map requestContext = dis.getRequestContext();
      requestContext.put(MessageContext.HTTP_REQUEST_METHOD, "GET");
      Source responseSource = dis.invoke(null);
     XMLHelper.prettyPrintXML(responseSource, System.out);
  }
}
In this class first i am creating a Service object pointing to http://localhost:9080/MyWebService/rest/contact/1 URL and then i am getting the Dispatcher object pointing to it. Next i use the RequestContext object to set the HTTP request method to GET and then i call the Dispatcher.invoke() which actually makes HTTP request and it returns Source object representing the response. Once i have the response i am uing the XMLHelper.prettyPrintXML() for pretty printing the XML, this is how the output looks like

No comments: