forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultipartBodyPublisher.java
More file actions
62 lines (45 loc) · 2.04 KB
/
Copy pathMultipartBodyPublisher.java
File metadata and controls
62 lines (45 loc) · 2.04 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package modern.challenge;
import java.io.IOException;
import java.util.Map;
import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class MultipartBodyPublisher {
private static final String LINE_SEPARATOR = System.lineSeparator();
public static HttpRequest.BodyPublisher ofMultipart(
Map<Object, Object> data, String boundary) throws IOException {
final byte[] separator = ("--" + boundary + LINE_SEPARATOR
+ "Content-Disposition: form-data; name=").getBytes(StandardCharsets.UTF_8);
final List<byte[]> body = new ArrayList<>();
for (Object dataKey : data.keySet()) {
body.add(separator);
Object dataValue = data.get(dataKey);
if (dataValue instanceof Path) {
Path path = (Path) dataValue;
String mimeType = fetchMimeType(path);
body.add(("\"" + dataKey + "\"; filename=\"" + path.getFileName()
+ "\"" + LINE_SEPARATOR + "Content-Type: "
+ mimeType + LINE_SEPARATOR + LINE_SEPARATOR)
.getBytes(StandardCharsets.UTF_8));
body.add(Files.readAllBytes(path));
body.add(LINE_SEPARATOR.getBytes(StandardCharsets.UTF_8));
} else {
body.add(("\"" + dataKey + "\""
+ LINE_SEPARATOR + LINE_SEPARATOR + dataValue + LINE_SEPARATOR)
.getBytes(StandardCharsets.UTF_8));
}
}
body.add(("--" + boundary + "--").getBytes(StandardCharsets.UTF_8));
return HttpRequest.BodyPublishers.ofByteArrays(body);
}
private static String fetchMimeType(Path filenamePath) throws IOException {
String mimeType = Files.probeContentType(filenamePath);
if (mimeType == null) {
throw new IOException("Mime type could not be fetched");
}
return mimeType;
}
}