在 Java 方法中,我想使用 Jersey 客户端对象对 RESTful Web 服务(也使用 Jersey 编写)执行 POST 操作,但不确定如何使用客户端发送将用作的值FormParam 在服务器上。我可以很好地发送查询参数。
我自己还没有做到这一点,但是 Google-Fu 的快速介绍揭示了 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);
有什么帮助吗?
从 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"
的格式发送。
示例 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);
如果您需要上传文件,则需要使用MediaType.MULTIPART_FORM_DATA_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);
最简单:
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);
你也可以尝试这个:
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
webResource.path("yourJerseysPathPost").queryParams(formData).post();
有没有办法在 body 中传递 null ?我试图在正文中传递任何内容,但收到 411 Length required 错误