Sending Objects to Restful Services via Post with Marshelling

Hi,

We all know that Restful services works with HTTP protocol. restful services support xml/jamson.

Problem: I have object and I want to send it “as is” to a restful service.

Solutions: 1. not straight forward: We need to convert that object manually to XML string and send it.
2. Straight forward:
2.a Annotate the object with those annotations:
Class annotations:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
Fields annotations:
@XmlElement(name=”fieldName”)

example:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class SomeObject implements Serializable
{
@XmlElement(name=”m”)
int m = 1;
@XmlElement(name=”g”)
int g = 2;
}

Now in order to send it we need to marshell our object using StringWriter and Marshaller.
Example:

Client side:

SomeObject myObject= new SomeObject();
HttpURLConnection conn = null;
StringWriter stringWriter = new StringWriter();

try
{
Marshaller m = JAXBContext.newInstance(SomeObject.class).createMarshaller();
m.marshal(myObject, stringWriter);

URL url = new URL(“http://localhost:8080/MYPROJECT_WEB/hello/testObjects”);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“Content-Type”, “application/xml”);

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

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

String output;
System.out.println(“Output from Server …. n”);
while ((output = br.readLine()) != null)
{
System.out.println(output);
}

}
catch (Exception e)
{

e.printStackTrace();

}
finally
{
conn.disconnect();

}

Server side:

@POST
@Path(“testObjects”)
//@Produces(“application/xml”)
@Consumes(“application/xml”)
// @Consumes(“text/*”)
@Produces(“text/plain”)
public String testObjects(GrandSun sun)
{
System.out.println(sun.toString());
return “Success”;
}

Idan.

Related Articles:

(2278)

Be Sociable, Share!

Leave a Reply