1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.hc.client5.http.examples;
28
29 import java.io.File;
30
31 import org.apache.hc.client5.http.classic.methods.HttpPost;
32 import org.apache.hc.client5.http.entity.mime.FileBody;
33 import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
34 import org.apache.hc.client5.http.entity.mime.StringBody;
35 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
36 import org.apache.hc.client5.http.impl.classic.HttpClients;
37 import org.apache.hc.core5.http.ContentType;
38 import org.apache.hc.core5.http.HttpEntity;
39 import org.apache.hc.core5.http.message.StatusLine;
40
41
42
43
44 public class ClientMultipartFormPost {
45
46 public static void main(final String[] args) throws Exception {
47 if (args.length != 1) {
48 System.out.println("File path not given");
49 System.exit(1);
50 }
51 try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
52 final HttpPost httppost = new HttpPost("http://httpbin.org/post");
53
54 final FileBody bin = new FileBody(new File(args[0]));
55 final StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
56
57 final HttpEntity reqEntity = MultipartEntityBuilder.create()
58 .addPart("bin", bin)
59 .addPart("comment", comment)
60 .build();
61
62
63 httppost.setEntity(reqEntity);
64
65 System.out.println("executing request " + httppost);
66 httpclient.execute(httppost, response -> {
67 System.out.println("----------------------------------------");
68 System.out.println(httppost + "->" + new StatusLine(response));
69 final HttpEntity resEntity = response.getEntity();
70 if (resEntity != null) {
71 resEntity.writeTo(System.out);
72 }
73 System.out.flush();
74 return null;
75 });
76 }
77 }
78
79 }