我想发送一个HTTP帖子,其中一个表单参数为File,另一个表单参数发送一个数字列表。
请求:
curl -X POST \
http://127.0.0.1:5001/verify \
-H 'cache-control: no-cache' \
-H 'content-type: multipart/form-data; boundary=----
-F 'items=["Apple", "Orange"]' \
-F 'photo=@/home/.../img.jpg'
答案 0 :(得分:0)
Client client = ClientBuilder.newBuilder()
.register(MultiPartFeature.class)
.build();
MultiPart multiPart = new FormDataMultiPart()
.field("items", "[\"Apple\", \"Orang\"]", MediaType.APPLICATION_JSON_TYPE)
.bodyPart(new FileDataBodyPart("photo", new File("img.png"));
Response response = client
.target(url)
.request()
.header(HttpHeaders.CACHE_CONTROL, "no-cache")
.post(Entity.entity(multiPart), multiPart.getMediaType());
为此,您需要添加依赖项
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey2.version}</version>
</dependency>
您标记了dropwizard,因此我假设您已经在使用/拥有Jersey客户端。如果你没有,那么添加
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey2.version}</version>
</dependency>