Saturday, January 25, 2014

Java client for posting to a Spring restful service

In my last post, http://mcdspringblog.blogspot.com/2014/01/posting-to-restful-service-from-spring.html, I talked about a Java client for retrieving a JSON object from a Spring-based, restful web service In this post, let's discuss how to use the same approach to post a JSON object to the same service.  Again, the client code is based on this post:

http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/


First, here's the service:

@RequestMapping(value="person3", method=RequestMethod.POST)
@ResponseBody
public Person postPerson(@RequestBody Person person) {
System.out.println("posting " + person.toString());
personService.save(person);
return person;


}

Note how it returns an object in the body of the response (JSON format).

Now let's create the client:

package com.codetutr.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

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

public class NetClientPost {

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

 try {


URL url = new URL("http://localhost:8081/spring-mvc-ajax-master/api/person3");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
Person person = new Person();
person.setName("John Smith");
person.setAge(33);


String input = new Gson().toJson(person, Person.class);

OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();


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 returnedPerson = gson.fromJson(sb.toString(), Person.class);
   System.out.println("returned person.name: " + returnedPerson.getName() + ", returned person.age: " + returnedPerson.getAge());
 

conn.disconnect();


 } catch (Exception e) {

System.out.println(e.getMessage());
e.printStackTrace();

 }

}

}

And here's the output:

Output from Server .... 


{"name":"John Smith","age":33}


Notes:

I initially got a "415" message from the server, media type not supported. Again the TCP Monitor from eclipse/STS came to the rescue (see my previous post on this). It showed the content-type was getting posted as url-encoded, as opposed to application/json. So, I just added this line:

conn.setRequestProperty("Content-Type", "application/json");

to the client, and we're good.

No comments:

Post a Comment