Complex query in Jersey REST call

Asked by At

I'm using com.sun.jersey.api.* to call REST service, I can't use another libraries and I need to make a bit more complex query like

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

Here is the code I tried so far, to just query Customer::name and... it fails.

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

By "it fails" I mean, I'm not receiving null on the server side instead of "Smith".

Edit

Well, I made obvious misstake, I need to post body, not query. Still...

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

That prints

{"customer": {"name" : "Smith"}}

And incomming request to server is null.

Tried to use the same JSON as body in Postman - it worked.

1 Answers

1
Hades On Best Solutions

I have s Sample code for Post request, If the JSON you mentioned is something which you want to receive at the server side, send the JSON in the Post body instead of as a request param, If its a request Param , Then check if you server expects the same key parameter i.e. customer.name

Sample code for Post with JSON data in body

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

              }

            }

Here is reference link for your help https://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/

After your edit set webResource.type("application/json")