簡體   English   中英

澤西島:如何使用帶有查詢參數和圖像的客戶端發出POST請求?

[英]Jersey: How to make a POST request using a Client with Query Parameters and an image?

我正在使用Jersey 2.22。 我的代碼:

   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));

這很好用,但是,我想包含一張圖像,但我不知道該怎么做。 我已經閱讀了文檔,卻找不到該怎么做。

因此,我發現存在一個jersey-media-multipart模塊。 我將其添加到我的依賴項中,並將代碼更改為:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM