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.io.entity.EntityUtils;
40 import org.apache.hc.core5.http.message.StatusLine;
41
42
43
44
45 public class ClientMultipartFormPost {
46
47 public static void main(final String[] args) throws Exception {
48 if (args.length != 1) {
49 System.out.println("File path not given");
50 System.exit(1);
51 }
52 try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
53 final HttpPost httppost = new HttpPost("http://localhost:8080" +
54 "/servlets-examples/servlet/RequestInfoExample");
55
56 final FileBody bin = new FileBody(new File(args[0]));
57 final StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
58
59 final HttpEntity reqEntity = MultipartEntityBuilder.create()
60 .addPart("bin", bin)
61 .addPart("comment", comment)
62 .build();
63
64
65 httppost.setEntity(reqEntity);
66
67 System.out.println("executing request " + httppost);
68 httpclient.execute(httppost, response -> {
69 System.out.println("----------------------------------------");
70 System.out.println(httppost + "->" + new StatusLine(response));
71 final HttpEntity resEntity = response.getEntity();
72 if (resEntity != null) {
73 System.out.println("Response content length: " + resEntity.getContentLength());
74 }
75 EntityUtils.consume(response.getEntity());
76 return null;
77 });
78 }
79 }
80
81 }