简体   繁体   中英

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

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 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM