简体   繁体   中英

How to send content and file as Multipart Form Data from Java using org.glassfish.jersey.media.multipart?

I want to send an HTTP post with one form parameter as File and Another one which sends a list of numbers.

Request:

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'

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

For this to work, you need to add the dependency

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>${jersey2.version}</version>
</dependency>

You tagged , so I assume you are already using/have Jersey client. If you don't then add

<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>${jersey2.version}</version>
</dependency>

See also

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM