简体   繁体   English

Java HTTP发布多部分

[英]Java HTTP Post Multipart

I'm trying to send an HTTP Post Multipart request to a local server in JAVA. 我正在尝试将HTTP Post Multipart请求发送到JAVA中的本地服务器。 I'm trying to send the following: 我正在尝试发送以下内容:

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

I've looked into Apache HTTP components, but it doesn't let me specify the content-type and disposition for each part. 我已经研究了Apache HTTP组件,但是不允许我为每个部分指定内容类型和配置。 Here's what I've written in JAVA using the Apache HTTP API: 这是我使用Apache HTTP API在JAVA中编写的内容:

`CloseableHttpClient httpclient = HttpClients.createDefault(); `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);

` `

FilePart和StringPart的构造函数参数和方法,与它们一起组成组成多部分请求的Part [],可以提供此信息。

Probably it is too late but as reference for anyone looking the answer for the same question, there is several methods in the MultipartEntityBuilder class that allow you to set the content-type and content-disposition for each part. 可能为时已晚,但是作为对寻找相同问题答案的任何人的参考, MultipartEntityBuilder类中有几种方法可以让您为每个部分设置内容类型和内容处置。 For example, 例如,

  • addBinaryBody(String name, File file, ContentType contentType, String filename) addBinaryBody(字符串名称,文件文件,ContentType contentType,字符串文件名)
  • addTextBody(String name, String text, ContentType contentType) addTextBody(字符串名称,字符串文本,ContentType contentType)

If we use the above methods in your example, 如果我们在您的示例中使用上述方法,

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM