Jersey POST 来自简单终端客户端的请求

Jersey POST request from simple terminal client

谁能告诉我如何从简单的终端客户端调用 post 请求?

    @POST
    @Path("insertt")
    public void insert(@QueryParam("id") Integer id,
                       @QueryParam("name") String name,
                       @QueryParam("lastname") String lastname,
                       @QueryParam("adress") String adress,
                       @QueryParam("city") String city ) {
        Customer cust = new Customer();
        cust.setCustomerId(id);
        cust.setName(name);
        cust.setLastNAme(lastname);
        cust.setAddressline1(adress);
        cust.setCity(city);
        customerDAO.add( cust );
    }

在客户端我做的:

Client c = ClientBuilder.newClient();   
WebTarget resource = c.target("http://localhost:8080/WebService/webresources/generic/insertt?id=100&name=test&lastname=test&adress=test&city=test");
//resource.request().post(); // This does not work

按照记录使用 curl 命令here:

... use curl to post this form with the same data filled in as before, we could do it like:

curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi This kind of POST will use the Content-Type application/x-www-form-urlencoded and is the most widely used POST kind.

The data you send to the server MUST already be properly encoded, curl will not do that for you. For example, if you want the data to contain a space, you need to replace that space with %20 etc. Failing to comply with this will most likely cause your data to be received wrongly and messed up.

Recent curl versions can in fact url-encode POST data for you, like this:

curl --data-urlencode "name=I am Daniel" http://www.example.com If you repeat --data several times on the command line, curl will concatenate all the given data pieces - and put a '&' symbol between each data segment.

  1. 因为您正在尝试发送 POST 数据 @QueryParam 将不起作用,因为 post 数据将作为请求正文而不是查询参数发送(这意味着不像你那样附加在 URL 中)。所以你必须改变你的资源方法如下:

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Path("insertt")
    public void insert(@FormParam("id") Integer id,
                       @FormParam("name") String name,
                       @FormParam("lastname") String lastname,
                       @FormParam("adress") String adress,
                       @FormParam("city") String city ) {
    
    Customer cust = new Customer();
    cust.setCustomerId(id);
    ...
    customerDAO.add( cust );
    

    }

  2. 并按如下方式更改您的客户端:

    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://localhost:8080/WebService/webresources/generic").path("insertt");
    Form form = new Form().param("id", "100").param("name", "test").param("lastname", "test").param("address", "test").param("city", "test");
    Response response = target.request().post(Entity.form(form));
    

此示例只是模拟 HTML 表单提交。如果您想以 XML 或 JSON 或任何其他形式发送数据,则必须查看 JAX-RS 文档。网上有很多资源;以下是一些示例网站:

注意:该示例使用 Jersey 2.23 和 Wildfly 8.2.1 进行了测试