Tuesday, January 21, 2014

Java client for retrieving a JSON object from a Spring restful service

I recently have been blogging about creating and using restful services in spring, e.g. "http://mcdspringblog.blogspot.com/2014/01/submitting-json-via-jquery-to-restful.html"

So, we know how to create the restful service, using the @RequestBody and @ResponsBody annotations, and how to call it from jQuery. But, what if we want to call it from inside some Java code?

To keep it as simple as possible, we'll use this service to call:

@RequestMapping("person/random")
@ResponseBody
public Person randomPerson() {
return personService.getRandom();

}

After some googling around, it seems that the simplest solution is to use java.net's HttpUrlConnection. We can use that to retrieve the json string from the request, and then convert it to a Person object using Google's Gson. Here's an modified version of a sample client found at http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/

package com.codetutr.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.codetutr.domain.Person;
import com.google.gson.Gson;

public class NetClientGet {

// http://localhost:8080/api/person/random
public static void main(String[] args) {

 try {

URL url = new URL("http://localhost:8080/spring-mvc-ajax-master/api/person/random");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
System.out.println(output);
sb.append(output);
}

   Gson gson = new Gson();
   Person person = gson.fromJson(sb.toString(), Person.class);
   System.out.println("Person.name: " + person.getName() + ", person.age: " + person.getAge());
   
conn.disconnect();

 } catch (MalformedURLException e) {

e.printStackTrace();

 } catch (IOException e) {

e.printStackTrace();

 }

}

}

And the output:

Output from Server .... 

{"name":"Robert Ford","age":16}
Person.name: Robert Ford, person.age: 16


Btw, in order to add Gson to the project, I added this line to the gradle build:

   compile 'com.google.code.gson:gson:2.2.4'

Then from the command line, ran this command:

gradle eclipse

Then refreshed the project, then ran a clean and build from STS/Eclipse. Note that I had to do a clean before the build worked correctly.



No comments:

Post a Comment