Using for REST Client

The JAX-WS has a 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 object, this is the code that i built for it.


import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.transform.Source;

public class DispatcherTest1 {

  public static void main(String[] args) {
    QName serviceName = new QName("", "svc");
      QName portName = new QName("", "port");
      Service svc = Service.create(serviceName);
      svc.addPort(portName, HTTPBinding.HTTP_BINDING,
      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: