在 REST 调用中传递多个参数

Pass Multiple parameters in a REST call

我的服务器代码如下:

@POST
@Path("/getMapping")
public ListResponse getMapping(Long id, String name, String clientName, String instanceName) {
    ListResponse response = null;
    try {
        response = new ListResponse();
        List<Mappings> mappings = service.getMapping(id, name, clientName, instanceName);
        response.setStatusCode(SUCCESS);
        response.setMappings(mappings);
    } catch (Exception e) {
        setResponseErrors(response, e);
    }
    return response;
}

我正在使用 Jersey REST 客户端,但我认为没有选项可以在 post 方法中传递多个参数,例如:

ClientResponse clientResponse = webResource.type(XML_TYPE).post(ClientResponse.class, id, name, clientName, instanceName);

有没有办法做到这一点?

在这种情况下,我可以使用 MultiValuedMap@QueryParams,但在其他情况下,多个参数是更复杂的对象。此外,将所有内容包装在 "paramContainer" 中将是一个低效的解决方案,因为有很多这样的方法具有多个具有不同组合的参数。

(顺便说一句,为什么 REST 不支持多个参数?)

非常感谢任何帮助。

这是我将如何做的 服务器代码

  • 1.1 必须使用@FormParam 才能在@FormDataParam 中声明参数
  • 1.2 a POST 如果为此用途加密则更好 @Consumes(MediaType.MULTIPART_FORM_DATA)

您将拥有这样的服务器代码:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/getMapping")
public ListResponse getMapping(@FormParam("id")Long id, @FormParam("name") String name, @FormParam("clientName") String clientName, @FormParam("instanceName") String instanceName) {
    ListResponse response = null;
    try {
        response = new ListResponse();
        List<Mappings> mappings = service.getMapping(id, name, clientName, instanceName);
        response.setStatusCode(SUCCESS);
        response.setMappings(mappings);
    } catch (Exception e) {
        setResponseErrors(response, e);
    }
    return response;
}

客户端代码

Form form = new Form();
form.add("id", "1");    
form.add("name", "je@rizze.com");
form.add("clientName","firefox");
form.add("instanceName","node45343.rizze.com");

ClientResponse response = webResource
  .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
  .post(ClientResponse.class, form); 

尽情享受吧:)

对上面 jeorfevre 的回答的补充:

如果您使用的是 Jersey 1.x,它是这样工作的:

客户端:(纯Java):

public Response testPost(String param1, String param2) {
    // Build the request string in this format:
    // String request = "param1=1&param2=2";
    String request = "param1=" + param1+ "&param2=" + param2;
    WebClient client = WebClient.create(...);
    return client.path(CONTROLLER_BASE_URI + "/test")
            .post(request);
}

服务器:

@Path("/test")
@POST
@Produces(MediaType.APPLICATION_JSON)
public void test(@FormParam("param1") String param1, @FormParam("param2") String param2) {
    ...
}