我正在尝试用JAVA向本地服务器发送一个HTTP Post多部分请求。我正在尝试发送以下内容:
{
"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 = 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);`
发布于 2014-07-09 01:12:31
FilePart和StringPart的构造函数参数和方法提供了此信息,您可以使用这两个参数和方法组成构成多部分请求的Part[]。
发布于 2015-01-29 06:50:24
也许为时已晚,但对于任何寻找相同问题答案的人来说,作为参考,MultipartEntityBuilder类中有几个方法允许您为每个部分设置内容类型和内容部署。例如,
如果我们在您的示例中使用上述方法,
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);https://stackoverflow.com/questions/24637316
复制相似问题