提问者:小点点

JavaHTTPPost Multipart


我正在尝试向JAVA中的本地服务器发送HTTPPost Multipart请求。我正在尝试发送以下内容:

{
 "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]
}

我研究了ApacheHTTP组件,但它不允许我为每个部分指定内容类型和配置。以下是我使用ApacheHTTPAPI用JAVA编写的内容:

'CloseableHttpClient httpclient=HttpClient. 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);

`


共2个答案

匿名用户

FilePart和StringPart的构造函数参数和方法(您使用它们组成组成多部分请求的Part[])提供了此信息。

匿名用户

可能为时已晚,但作为寻找同一问题答案的任何人的参考,MultipartEntityBuilder类中有几个方法允许您为每个部分设置内容类型和内容处置。例如,

  • addBinaryBody(字符串名、文件文件、ContentType contentType、字符串文件名)
  • addTextBody(字符串名称、字符串文本、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);