如何使用Apache Wink RestClient将JSON数据发布到web服务?

时间:2022-02-27 15:16:45

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

我试图通过在Java中发布JSON数据来测试JAX-RS。

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

我使用的是Apache Wink 1.0和Apache Wink RestClient。医生说这就是你写文章的方式……

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?

…但是,我要对JSON数据进行哪些更改呢?

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".

…但是,我在POST上得到了一个例外,这个错误是:“没有编写类net.sf.json的作者。JSONObject和媒体类型应用程序/json。

Any ideas or suggestions are greatly appreciated!

如有任何意见或建议,我们将不胜感激!

Rob

罗伯

1 个解决方案

#1


1  

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:

您的代码看起来非常正确,除了我希望post是用字符串实体完成的。因此,你可能想要改变:

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

#1


1  

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:

您的代码看起来非常正确,除了我希望post是用字符串实体完成的。因此,你可能想要改变:

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