我尝试将HTTP Post Multipart请求发送到JAVA中的本地服务器。我试图发送以下内容:
{
"content-disposition": "form-data; name=\"metadata\"",
"content-type": "application/x-dmas+json",
"body": JSON.stringify(client_req)
},
{
"content-disposition": "attachment; filename=\"" + file + "\"; name=\"file\"",
"content-type": "application/octet-stream",
"body": [file content]
}
我查看过Apache HTTP组件,但它并没有让我指定每个部分的内容类型和处置方式。以下是我使用Apache HTTP API在JAVA中编写的内容:
`CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("IP");
FileBody bin = new FileBody(new File(args[0]), "application/octet-stream");
StringBody hash = new StringBody("{\"hash\": \"\", \"policy\": {\"retention_permitted\": true, \"distribution\": \"global\"}}", ContentType.create("application/x-dmas+json"));
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("metadata", hash)
.addPart("file", bin)
.build();
httppost.setEntity(reqEntity);
`
答案 0 :(得分:0)
FilePart和StringPart的构造函数参数和方法,您使用它们组成构成多部分请求的Part [],提供此信息。
答案 1 :(得分:0)
可能为时已晚,但作为对同一问题的答案的任何人的参考,MultipartEntityBuilder类中有几种方法允许您为每个部分设置内容类型和内容处置。例如,
- addBinaryBody(String name,File file,ContentType contentType,String filename)
- addTextBody(String name,String text,ContentType contentType)
如果我们在您的示例中使用上述方法,
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("http://url-to-post/");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
String jsonStr = "{\"hash\": \"\", \"policy\": {\"retention_permitted\": true, \"distribution\": \"global\"}}";
builder.addTextBody("metadata", jsonStr, ContentType.create("application/x-dmas+json"));
builder.addBinaryBody("file", new File("/path/to/file"),
ContentType.APPLICATION_OCTET_STREAM, "filename");
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
HttpResponse response = httpClient.execute(uploadFile);