Saturday, July 2, 2011

Posting a JSON Request into RESTful Interface

In the earlier article, we have seen how to host a REST interface accepting JSON message as an input and sending JSON message as a response.
Here, we will post a JSON message into the same rest interface that we have hosted earlier and accept a JSON message in the response.
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.codehaus.jettison.json.JSONObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

public class TestSampleRestInterface {
      public static void main(String[] args) {
            ClientConfig config = new DefaultClientConfig();
            Client client = Client.create(config);


//if timeouts needs to be configured then please add the following lines

           //Set the connection time out (milliseconds)
          client.setConnectTimeout(5000);

           //Set the read time out (in milliseconds)
          client.setReadTimeout(5000);


               /*if host has restricted access while connecting to the server by       weblogic basic authentication. Please add the following lines with proper credentials*/

         client.addFilter(new HTTPBasicAuthFilter(“username”,”password”);


            WebResource service = client.resource(getBaseURI());
                  JSONObject object = null;
            try {
                  object = new JSONObject();
                  object.put("firstname","Snehanshu");
                  object.put("lastname","Chatterjee");
                  object.put("company","TM");
                  object.put("grade","TA");
                  object.put("post","G1");     
                  System.out.println(object);
            } catch (Exception e) {
                  e.printStackTrace();
            }
            long startTime = System.currentTimeMillis();
                  System.out.println("Response :"
                              + service.accept(
                                          MediaType.APPLICATION_JSON).post(JSONObject.class,
                                          object));  
            long endTime = System.currentTimeMillis();
            System.out.println(startTime-endTime);
      }

      private static URI getBaseURI() {
            return UriBuilder.fromUri(
                        "http://localhost:7001/samplerest/sampleRequest")
                        .build();
      }
}
Output:
{"EmployeeHeader":{"errorCode":"0","errorText":"Employee Creation Successful"}}

For any calls to rest interfaces which accept get request with variable inputs, the following line of codes need to be added.

//to accept a response on top of any get request

responseString = service.queryParams(queryParams).accept(MediaType.APPLICATION_XML).get(String.class);

//to add the variable inputs with ?_id=”anyvalue”
MultivaluedMap&lt:String, String> queryParams = new MultivaluedMapImpl();
queryParams.add(id, ID);

While connecting through proxy, please add the following lines before connecting to remote server

System.getProperties().setProperty(“http.proxySet”,”true”);
System.getProperties().setProperty(“http.proxyHost”,”111.222.111.222”);
System.getProperties().setProperty(“http.proxyPort”,”8080”);

Hope you find it useful.

No comments:

Total Pageviews