不幸的是,Java 11 HTTP 客户端没有为多部分类型的主体提供任何方便的支持。但是我们可以在它之上构建自定义实现:
Map<Object, Object> data = new LinkedHashMap<>();
data.put("token", "some-token-value";);
data.put("file", File.createTempFile("temp", "txt").toPath(););
// add extra parameters if needed
// Random 256 length string is used as multipart boundary
String boundary = new BigInteger(256, new Random()).toString();
HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.header("Content-Type", "multipart/form-data;boundary=" + boundary)
.POST(ofMimeMultipartData(data, boundary))
.build();
public HttpRequest.BodyPublisher ofMimeMultipartData(Map<Object, Object> data,
String boundary) throws IOException {
// Result request body
List<byte[]> byteArrays = new ArrayList<>();
// Separator with boundary
byte[] separator = ("--" + boundary + "\r\nContent-Disposition: form-data; name=").getBytes(StandardCharsets.UTF_8);
// Iterating over data parts
for (Map.Entry<Object, Object> entry : data.entrySet()) {
// Opening boundary
byteArrays.add(separator);
// If value is type of Path (file) append content type with file name and file binaries, otherwise simply append key=value
if (entry.getValue() instanceof Path) {
var path = (Path) entry.getValue();
String mimeType = Files.probeContentType(path);
byteArrays.add(("\"" + entry.getKey() + "\"; filename=\"" + path.getFileName()
+ "\"\r\nContent-Type: " + mimeType + "\r\n\r\n").getBytes(StandardCharsets.UTF_8));
byteArrays.add(Files.readAllBytes(path));
byteArrays.add("\r\n".getBytes(StandardCharsets.UTF_8));
} else {
byteArrays.add(("\"" + entry.getKey() + "\"\r\n\r\n" + entry.getValue() + "\r\n")
.getBytes(StandardCharsets.UTF_8));
}
}
// Closing boundary
byteArrays.add(("--" + boundary + "--").getBytes(StandardCharsets.UTF_8));
// Serializing as byte array
return HttpRequest.BodyPublishers.ofByteArrays(byteArrays);
}
这是Github 上的工作示例(您需要更改 VirusTotal API 密钥)