java – Jersey客户端/ JAX-RS和可选(不是默认)@QueryParam(客户
我有一个RESTful API,他的文档说,某个查询参数是可选的,不提供默认参数.所以,我可以提供该值,也可以不在GET请求中发送它作为参数.
例: > queryA是必需的 这应该工作: http://www.example.com/service/endpoint?queryA=foo&queryB=bar 这也应该有效: http://www.example.com/service/endpoint?queryA=foo 如何为Jersey-Proxy的客户端界面做到这一点?我没有服务器端代码来连接,所以我通过Jersey-Proxy使用org.glassfish.jersey.client.proxy.WebResourceFactory来生成客户端与服务器API进行交互. 示例界面: import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @Path("/service") @Produces("application/json") public interface ServiceInterface { @Path("/endpoint") @GET public Response getEndpoint( @QueryParam("queryA") String first,@QueryParam("queryB") String second); } 我知道我可以做另外一种方法: @Path("/endpoint") @GET public Response getEndpoint( @QueryParam("queryA") String first); 但是当您有多个可选字段时会发生什么?我不想让他们的每一个可能的突变! 解决方法
界面是一直的
我不敢相信这是容易的: import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @Path("/service") @Produces("application/json") public interface ServiceInterface { @Path("/endpoint") @GET public Response getEndpoint( @QueryParam("queryA") String first,@QueryParam("queryB") String second); } 注意什么不同于问题界面?不.那是因为那是答案! 不要使用@DefaultValue 如果要将参数默认为特定值,请在参数中使用@DefaultValue注释: import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @Path("/service") @Produces("application/json") public interface ServiceInterface { @Path("/endpoint") @GET public Response getEndpoint( @QueryParam("queryA") String first,@QueryParam("queryB") @DefaultValue("default") String second); } 将null传递给您不想要的@QueryParam 如果要使@QueryParam可选,则不应用@DefaultValue注释.要使用query参数传递值,只需正常传递值.如果您希望查询参数不显示,只需传递null! import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @Path("/service") @Produces("application/json") public interface ServiceInterface { @Path("/endpoint") @GET public Response getEndpoint( @QueryParam("queryA") String first,// Pass null to this parameter to not put it in the GET request @QueryParam("queryB") String second); } 所以调用ServiceInterface.getEndpoint(“firstQueryParam”,“secondQueryParam”);要求: http://targethost.com/service/endpoint?queryA=firstQueryParam&queryB=secondQueryParam 并调用ServiceInterface.getEndpoint(“firstQueryParam”,null);要求: http://targethost.com/service/endpoint?queryA=firstQueryParam 和瓦拉!没有第二个查询参数! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |