将其余Web服务的输入类型设置为Json

时间:2013-08-28 08:09:51

标签: java json web-services rest

我正在使用其他Web服务,我正在通过FF中的Rest Client执行它。直到现在它被用作post方法现在我要将它的输入类型更改为JSON,即现在我将json输入发送到那个ws但是在休息客户端我正在获取

Status Code: 415 Unsupported Media Type
Connection: Keep-Alive
Content-Length: 0
Content-Type: text/plain
Date: Wed, 28 Aug 2013 07:52:50 GMT
Keep-Alive: timeout=5, max=99
Server: Apache/2.2.19 (Win32) mod_jk/1.2.30 PHP/5.3.6

下面是ws的新签名(我添加了Consume and Produce Line)

@Override
    @POST
    @Path("/addHouseHoldAccounts")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response addHouseHoldAccounts(JSONObject jsonObject) {
....
....
}

在休息客户端上我设置了标题Content-Type application/json

以下是我正在尝试发送的JSON输入

{
   "jsonObject":{
       "JsonId":"17fb00b6-dfa3-4cc6-b7ba-c54ecd429350",
   "JsonTypeOf":"JSonTest",
   "JsonType":"",
   "JsonTypetName":"JsonImplemented"
   }
}

任何人都可以指出我的错误或建议我实现这个目标的解决方案。

2 个答案:

答案 0 :(得分:0)

尝试将请求标题"Accept"设置为"application/json"

http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#z3

答案 1 :(得分:0)

我认为此代码可以为您提供帮助:

WebService的:

        @POST
        @Path("/your_path")

        @Consumes(MediaType.APPLICATION_JSON)
        @Produces(MediaType.APPLICATION_JSON)

        //Receive and send a json object
        public JSONObject receiveJSONObject(JSONObject json) throws JSONException
        {
               return json;
        }

客户端

private void sendJSONObject() throws JSONException{

        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        client.addFilter(new LoggingFilter());
        WebResource service = client.resource("*your_adress_and_path*");
        JSONObject data= new JSONObject();
        dados.put("Name", "John");
        dados.put("Age", "30");
        dados.put("City", "Tokyo");

        ClientResponse client_response = service.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, data);

        System.out.println("Status: "+client_response.getStatus());

        client.destroy();

    }

我不确定,但我认为你没有将内容类型设置为json。这段代码对我有用。