【问题标题】:Java HTTP Post MultipartJava HTTP Post 多部分
【发布时间】:2014-08-29 12:18:39
【问题描述】:

我正在尝试向 JAVA 中的本地服务器发送 HTTP Post 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]
}

我研究了 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);

`

【问题讨论】:

  • 那不是 Java 而是 JavaScript。向我们展示相关的 Java 代码。
  • 不过,我希望能够在 JAVA 中为每个部分设置 content-type 和 content-disposition。

标签: java http multipartform-data


【解决方案1】:

FilePart 和 StringPart 的构造函数参数和方法,用于组成构成多部分请求的 Part[] 提供此信息。

【讨论】:

  • 这可以与 MultipartEntityBuilder 一起使用吗?我已经看到它与已弃用的 MultipartRequestEntity 一起使用。
【解决方案2】:

可能为时已晚,但作为任何寻找同一问题答案的人的参考,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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    相关资源
    最近更新 更多