首页 > 解决方案 > Jersey REST 调用中的复杂查询

问题描述

com.sun.jersey.api.*用来调用 REST 服务,我不能使用其他库,我需要做一些更复杂的查询,比如

"customer" : { 
    "name": "Smith", 
    "documents" : 
    [{"id" : "100", "content" : "lorem"}, 
    {"id" : "101", "content" : "ipsum"}] 
}

 

这是我到目前为止尝试的代码,只是查询Customer::name并且......它失败了。

 Client client = Client.create();
 WebResource resource = client.resource(URL);
 String response = resource.queryParam("customer.name", "Smith")
                   .accept(MediaType.APPLICATION_FORM_URLENCODED)
                   .post(String.class);

         

“它失败了”我的意思是,我没有null在服务器端而不是“Smith”接收。

编辑

好吧,我犯了明显的错误,我需要发布正文,而不是查询。仍然...

 String body =  "{\"customer\": {\"name\" : \"Smith\"}}";
 String s = resource
             .accept(MediaType.APPLICATION_FORM_URLENCODED)
              .post(String.class, body);
 System.out.println(body);          

那打印

{“客户”:{“名称”:“史密斯”}}

对服务器的传入请求是null.

尝试在 Postman 中使用与正文相同的 JSON - 它有效。

标签: javarestjersey

解决方案


我有 Post 请求的示例代码,如果您提到的 JSON 是您想要在服务器端接收的东西,请在 Post 正文中发送 JSON 而不是作为请求参数,如果它是请求参数,然后检查您是否服务器需要相同的关键参数,即 customer.name

正文中带有 JSON 数据的 Post 示例代码

     public static void main(String[] args) {

            try {

                Client client = Client.create();

                WebResource webResource = client
                   .resource("http://localhost:8080/RESTfulExample/rest/foo");

                String input = "{
    \"customer\": {
        \"name\": \"Smith\",
        \"documents\": [{
                \"id\": \"100\",
                \"content\": \"lorem\"
            },
            {
                \"id\": \"101\",
                \"content\": \"ipsum\"
            }
        ]
    }
}";

                ClientResponse response = webResource.type("application/json")
                   .post(ClientResponse.class, input);

                if (response.getStatus() != 201) {
                    throw new RuntimeException("Failed : HTTP error code : "
                         + response.getStatus());
                }

                System.out.println("Output from Server .... \n");
                String output = response.getEntity(String.class);
                System.out.println(output);

              } catch (Exception e) {

                e.printStackTrace();

              }

            }

这是您帮助的参考链接 https://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/

编辑后 设置 webResource.type("application/json")


推荐阅读