如何使用Java创建multipart / form-data POST请求? [英] How can I make a multipart/form-data POST request using Java?

查看:1363
本文介绍了如何使用Java创建multipart / form-data POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Apache Commons HttpClient版本3.x的时代,可以进行多部分/表单数据POST请求( 2004年的一个例子)。不幸的是,这在 HttpClient 4.0版本中已不再可能。

In the days of version 3.x of Apache Commons HttpClient, making a multipart/form-data POST request was possible (an example from 2004). Unfortunately this is no longer possible in version 4.0 of HttpClient.


对于我们的核心活动HTTP,multipart有点超出范围
。我们喜欢使用由一些
其他项目维护的多部分代码,但是我不知道。
我们尝试将多部分代码移动到commons-codec几年前的b
,但我没有在那里起飞。 Oleg最近提到了另一个
项目,它有多部分解析代码,可能对我们的多部分格式代码感兴趣
。我不知道当前状态
。 ( http://www.nabble.com/multipart-form- data-in-4.0-td14224819.html

是否有人知道任何允许我编写的Java库可以发出multipart / form-data POST请求的HTTP客户端?

Is anybody aware of any Java library that allows me to write an HTTP client that can make a multipart/form-data POST request?

背景:我想使用 Zoho Writer的远程API

推荐答案

我们使用HttpClient 4.x来制作多部分文件。

We use HttpClient 4.x to make multipart file post.

更新:从 HttpClient 4.3 开始,一些类已被弃用。以下是具有新API的代码:

UPDATE: As of HttpClient 4.3, some classes have been deprecated. Here is the code with new API:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

// This attaches the file to the POST:
File f = new File("[/path/to/upload]");
builder.addBinaryBody(
    "file",
    new FileInputStream(f),
    ContentType.APPLICATION_OCTET_STREAM,
    f.getName()
);

HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();

以下是弃用的HttpClient 4.0 API 的原始代码片段:

Below is the original snippet of code with deprecated HttpClient 4.0 API:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

这篇关于如何使用Java创建multipart / form-data POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆