Java 如何将多个参数传递给 Jersey POST 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39201759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:57:51  来源:igfitidea点击:

How to pass multiple parameters to Jersey POST method

javarestjersey

提问by Terance

I am trying to pass multiple parameters to Jersey POST method . Currently I am following below steps to pass a single parameter to Jersey POST method.

我正在尝试将多个参数传递给 Jersey POST 方法。目前我正在按照以下步骤将单个参数传递给 Jersey POST 方法。

Client client = ClientBuilder.newClient();
WebTarget target= client.target("http://localhost:8080/Rest/rest/subuser").path("/insertSubUser");

SubUserBean subUserBean=new SubUserBean();
subUserBean.setIdUser(1);
subUserBean.setIdSubUserType(1);
subUserBean.setIdSubUser(15);
subUserBean.setFirstName("Haritha");
subUserBean.setLastName("Wijerathna");
subUserBean.setNumberOfDaysToEditRecord(14);
subUserBean.setUserName("haritha");
subUserBean.setPassword("hariwi88");
subUserBean.setDateCreated(Common.getSQLCurrentTimeStamp());
subUserBean.setLastUpdated(Common.getSQLCurrentTimeStamp());

target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(subUserBean, MediaType.APPLICATION_JSON_TYPE));

SubUserJSONService.java

子用户JSONService.java

@Path("/subuser")
public class SubUserJSONService {

    @POST
    @Path("/insertSubUser")
    @Consumes(MediaType.APPLICATION_JSON)
    public String updateSubUser(SubUserBean bean){

        SubUserInterface table = new SubUserTable();
        String result= table.insertSubUser(bean);
        return result;
    }
}

Now, I want to pass parameters to following method via Jersey POST method.

现在,我想通过 Jersey POST 方法将参数传递给以下方法。

public String insertHistory(List<SocialHistoryBean> list, String comment){
    //my stuffs
}

Have any ideas to do above work ?

对以上工作有什么想法吗?

Thank you.

谢谢你。

回答by Sheetal Mohan Sharma

You can try using MultivaluedMap.Add form data and send it to the server. An example below, code is not tested just for demo/logic flow.

您可以尝试使用MultivaluedMap。新增表格数据并将其发送到服务器。下面是一个示例,代码不只是针对演示/逻辑流程进行测试。

WebTarget webTarget = client.target("http://www.example.com/some/resource");
    MultivaluedMap<List, String> formData = new MultivaluedHashMap<List, String>();
    formData.add(List, "list1");
    formData.add("key2", "value2");
    Response response = webTarget.request().post(Entity.form(formData));

Consume this on server side something like

在服务器端消费这个东西

@Path("/uripath")
@POST -- if this is post or @GET
@Consumes("application/x-www-form-urlencoded;charset=UTF-8") or json..
@Produces("application/json")
public void methodNameHere(@FormParam("list") List<String> list1, @FormParam("key2") String val2) {

    System.out.println("Here are I am");
    System.out.println("list1" + list1.size);
    System.out.println("val2" + val2);
}

Read more herein docs..

在文档中阅读更多信息..

回答by dsp_user

JSON data cannot be passed to the server in a List. This means that you should create a wrapper around your SocialHistoryBean class (i.e around the list that holds your objects)

JSON 数据不能以列表的形式传递给服务器。这意味着您应该围绕您的 SocialHistoryBean 类(即围绕保存您的对象的列表)创建一个包装器

 @XmlRootElement(name = "uw")
 public class SocialHistoryBeanWrapper implements Serializable {

private List<SocialHistoryBean> sList ;//this will hold your SocialHistoryBean instances
public SocialHistoryBeanWrapper(){
    sList = new ArrayList<User>();

    }
public List<User> getUsrList(){
    return sList;
}
    }

Your server side code will be like

您的服务器端代码将类似于

@POST
@Path("/history")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String insertHistory( @QueryParam("comment") String comment, SocialHistoryBeanWrapper uw) {
    do whatever you want with your history data
    //userData.setUser(uw.getUsrList().get(0));

    return comment; //just echo the string that we have  sent from client

}

Note that comment is passed with @QueryParam (this means it's not part of the POST request (body) but is rather encoded in the URL string. For this to work, you can call your service as (the client code)

请注意,注释是通过@QueryParam 传递的(这意味着它不是 POST 请求(正文)的一部分,而是编码在 URL 字符串中。为此,您可以将您的服务称为(客户端代码)

 WebTarget target = client.target(UriBuilder.fromUri("http://localhost:8088/Rest/rest/subuser").build());    

SocialHistoryBeanWrapper uw = new SocialHistoryBeanWrapper();

      //just populate whatever fields you have;
        uw.getUsrList().get(0).setName("Mark Foster");
        uw.getUsrList().get(0).setProfession("writer");
        uw.getUsrList().get(0).setId(55);


        String s = target.path("history").queryParam("comment", "OK").request()
                   .accept(MediaType.TEXT_PLAIN).post(Entity.entity(uw, MediaType.APPLICATION_JSON), String.class);

        System.out.println(s);//this prints OK

回答by Naor Bar

In case you're using Jersey 1.x, check this example on how to post multiple objects as @FormParam

如果您使用的是 Jersey 1.x,请查看此示例以了解如何将多个对象作为 @FormParam 发布

Client: (pure Java):

客户端:(纯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);
}

Server:

服务器:

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