Jersey REST调用中的复杂查询

时间:2019-05-10 05:50:08

标签: java rest jersey

我正在使用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中的body相同的JSON-它起作用。

1 个答案:

答案 0 :(得分:1)

我有一个用于Post请求的示例代码,如果您提到的JSON是要在服务器端接收的东西,请在Post正文中发送JSON而不是作为请求参数,如果它是请求Param,则检查服务器是否期望使用相同的关键参数,即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”)

相关问题