Post/Put/Delete http Json with additional parameters in Jersey + general design issues

六月ゝ 毕业季﹏ 提交于 2019-12-03 03:58:35

I am not sure I understand what you are trying to achieve. Let me try explain a few things - hope it will be relevant to your question: @QueryParam injects parameters which are part of your path - i.e. the part of the URL that goes after "?". E.g. if you have a URL like this: http://yourserver.com/person/personCode/resourceName?resourceData=abc&token=1234

Then there would be 2 query params - one named resourceData with value "abc" and the other one named token with value "1234".

If you are passing an entity in the POST request, and that entity is of application/json type, you can simply annotate your post method using @Consumes("application/json") annotation and add another parameter to your method, which does not need to be annotated at all. That parameter can be either a String (in that case Jersey would pass a raw JSON string and you would have to parse it yourself) or it can be a java bean annotated with @XmlRootElement annotation - in that case (if you also include jersey-json module on your classpath) Jersey will try to unmarshall the json string into that object using JAXB. You can also use Jackson or Jettison libraries to do that - see this section of Jersey User Guide for more info: http://jersey.java.net/nonav/documentation/latest/json.html

Found!

Client side:

Client c = Client.create();
WebResource service = c.resource("www.yourserver.com/");
String s = service.path("test/personCode/resourceName")
                .queryParam("auth_token", "auth")
                .type("text/plain")
                .post(String.class, jsonString);

Server side:

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

@Path("/test/{personCode}/{resourceName}")
public class TestResourceProvider {

@POST
@Consumes("text/plain")
@Produces("application/json")
public String postUserResource(String jsonString,                                              
                               @PathParam("personCode") String personCode,                                                                                      
                               @PathParam("resourceName") String resourceName,                                                   
                               @QueryParam("auth_token") String auth_token)                                                  
                               throws UnhandledResourceException {

    //Do whatever...    

    }
}

In my case, I will parse the json I get in the server depending on the resource name, but you can also pass the object itself, and make the server consume an "application/json".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!