简体   繁体   English

泽西岛:如何使用带有查询参数和图像的客户端发出POST请求?

[英]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.

相关问题 如何使用Jersey客户端为每个POST请求建立新连接 - How to make a new connection for each POST request with Jersey Client 如何使用Jersey 2.26客户端与queryParam进行HTTP POST请求? - How to do HTTP POST request with queryParam using Jersey 2.26 client? 使用jersey客户端编写POST请求 - Writing a POST request using a jersey client 如何使Jersey Rest POST请求同步 - How to make Jersey Rest POST request to be synchronized 如何将查询参数发送到Java客户端的POST请求并使用@QueryParam接收 - How to send query parameters to POST request from Java client, and receive using @QueryParam 使用jersey客户端使用请求参数和请求正文执行POST操作 - Using the jersey client to do a POST operation with request params and a request body 如何在 Jersey 客户端 HTTP POST 请求中发布原始 json 文本? - How to post raw json text in Jersey Client HTTP POST request? 如何使用 Java 中的新 HTTP 客户端在 POST() 请求中传递参数 - How to pass parameters in a POST() request using the new HTTP client in Java 如何在发布请求中使用 jersey(jax-rs) 客户端将 object 作为另一个 object 的属性传递? - How to pass an object as an attribute of another object using jersey(jax-rs) client in a post request? 泽西岛客户端-如何以带有POST请求的形式发送列表 - Jersey Client - How to send List in a form with a POST request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM