[英]Jersey: How to make a POST request using a Client with Query Parameters and an image?
I'm using Jersey 2.22. 我正在使用Jersey 2.22。 My code:
我的代码:
WebTarget target = ClientBuilder.newClient().target("https://api.someurl.com");
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.add("param1", "1");
map.add("param2", "2");
map.add("param3", "3");
Response response = target.request().post(Entity.form(map));
This works well, however, I want to include an image and I have no idea how to do it. 这很好用,但是,我想包含一张图像,但我不知道该怎么做。 I've read the documentation and couldn't find how to do it.
我已经阅读了文档,却找不到该怎么做。
So, I found out that a jersey-media-multipart
module existed. 因此,我发现存在一个
jersey-media-multipart
模块。 I added it to my dependencies and changed my code to: 我将其添加到我的依赖项中,并将代码更改为:
Client client = ClientBuilder.newClient();
client.register(MultiPartFeature.class);
WebTarget target = client.target("https://apisomeurl.com");
MultiPart multiPart = new MultiPart();
multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
//Image here
FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("image", new File("/some/img/path/img.png"));
multiPart.bodyPart(fileDataBodyPart);
//MediaType.APPLICATION_JSON_TYPE because I'm expecting a JSON response from the server
String str = target.queryParam("param1", "1")
.queryParam("param2", "2")
.queryParam("param3", "3")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(multiPart, multiPart.getMediaType()), String.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.