首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java HTTP Post Multipart

Java HTTP Post Multipart
EN

Stack Overflow用户
提问于 2014-07-09 00:44:07
回答 2查看 1.1K关注 0票数 0

我正在尝试用JAVA向本地服务器发送一个HTTP Post多部分请求。我正在尝试发送以下内容:

代码语言:javascript
复制
{
 "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();

代码语言:javascript
复制
    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);

`

EN

回答 2

Stack Overflow用户

发布于 2014-07-09 01:12:31

FilePart和StringPart的构造函数参数和方法提供了此信息,您可以使用这两个参数和方法组成构成多部分请求的Part[]。

票数 0
EN

Stack Overflow用户

发布于 2015-01-29 06:50:24

也许为时已晚,但对于任何寻找相同问题答案的人来说,作为参考,MultipartEntityBuilder类中有几个方法允许您为每个部分设置内容类型和内容部署。例如,

  • addBinaryBody(String名称,文件文件,文本文件,字符串文本名称,字符串文本,contentType contentType)

如果我们在您的示例中使用上述方法,

代码语言:javascript
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24637316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档