how to post JSON data to web service using Apache Wink RestClient?

user550738 picture user550738 · Mar 2, 2012 · Viewed 9.4k times · Source

I'm trying to test a JAX-RS by doing a POST of JSON data from Java.

I'm using Apache Wink 1.0, and the Apache Wink RestClient. The docs say this is how you do a POST ...

RestClient client = new RestClient();
Resource resource = client.resource("http://services.co");
String response = resource.contentType("text/plain").accept("text/plain").post(String.class, "foo");

... but what changes do I make to POST JSON data?

I tried this:

JSONObject json = new JSONObject();
json.put("abc", 123);

RestClient client = new RestClient();
Resource resource = client.resource("http://services.co");
JSONObject response = resource.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(JSONObject.class, json);

... but I on POST I get an exception with this error: "No writer for type class net.sf.json.JSONObject and media type application/json".

Any ideas or suggestions are greatly appreciated!

Rob

Answer

Perception picture Perception · Mar 2, 2012

Your code looks pretty much correct except that I would expect the post to be done with a String entity. As such you may want to change:

JSONObject response = resource.contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON).post(JSONObject.class, json);

To:

String response = resource.contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON).post(String.class, json);