代码之家  ›  专栏  ›  技术社区  ›  Jon Onstott

使用Jersey客户端执行POST操作

  •  52
  • Jon Onstott  · 技术社区  · 16 年前

    在Java方法中,我希望使用Jersey客户端对象对RESTful web服务(也使用Jersey编写)执行POST操作,但不确定如何使用客户端发送将用作服务器上FormParam的值。我可以发送查询参数。

    6 回复  |  直到 8 年前
        1
  •  87
  •   Gabriel Saraiva brabster    10 年前

    tech tip on blogs.oracle.com 举例说明你的要求。

    来自博客帖子的示例:

    MultivaluedMap formData = new MultivaluedMapImpl();
    formData.add("name1", "val1");
    formData.add("name2", "val2");
    ClientResponse response = webResource
        .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
        .post(ClientResponse.class, formData);
    

        2
  •  53
  •   tonga    11 年前

    从Jersey 2.x开始 MultivaluedMapImpl 类被替换为 MultivaluedHashMap . 您可以使用它添加表单数据并将其发送到服务器:

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

    "application/x-www-form-urlencoded" .

        3
  •  18
  •   Olivier Tonglet    6 年前

    Jersey Client documentation

    例5.1。带有表单参数的POST请求

    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://localhost:9998").path("resource");
    
    Form form = new Form();
    form.param("x", "foo");
    form.param("y", "bar");
    
    MyJAXBBean bean =
    target.request(MediaType.APPLICATION_JSON_TYPE)
        .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
            MyJAXBBean.class);
    
        4
  •  5
  •   dimuthu    12 年前

    如果需要上传文件,则需要使用MediaType.MULTIPART\u FORM\u DATA\u TYPE。 看起来MultivaluedMap不能与之一起使用,所以这里有一个使用FormDataMultiPart的解决方案。

    InputStream stream = getClass().getClassLoader().getResourceAsStream(fileNameToUpload);
    
    FormDataMultiPart part = new FormDataMultiPart();
    part.field("String_key", "String_value");
    part.field("fileToUpload", stream, MediaType.TEXT_PLAIN_TYPE);
    String response = WebResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);
    
        5
  •  3
  •   supercobra    11 年前

    最简单的:

    Form form = new Form();
    form.add("id", "1");    
    form.add("name", "supercobra");
    ClientResponse response = webResource
      .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
      .post(ClientResponse.class, form);
    
        6
  •  2
  •   Michal Kordas FrantiÅ¡ek Hartman    11 年前

    您也可以尝试以下方法:

    MultivaluedMap formData = new MultivaluedMapImpl();
    formData.add("name1", "val1");
    formData.add("name2", "val2");
    webResource.path("yourJerseysPathPost").queryParams(formData).post();
    
    推荐文章