2

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

  • Your code looks pretty much on point except that I would expect the `.post` to be with `String.class`, not `JSONObject.class`. – Perception Mar 02 '12 at 17:26
  • Thanks, changed to 'String response = resource.content ... post(String.class, json)' and now the client is happy. However, I have a new server problem, I'm adding a new question -- please help! :) Thanks! http://stackoverflow.com/questions/9538342/whats-wrong-with-my-simple-json-jax-rs-web-service –  Mar 02 '12 at 18:17
  • @Perception - Please post your comment as an answer, and I'll mark it correct! –  Mar 02 '12 at 18:18
  • Thanks -- please look at my new question too, I'm rather stuck. –  Mar 02 '12 at 18:41
  • Dead link to docs. –  Jul 18 '16 at 15:37

1 Answers1

0

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);
Perception
  • 79,279
  • 19
  • 185
  • 195