为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用Java进行多部分/表单数据发布请求?

如何使用Java进行多部分/表单数据发布请求?

12345678_0001 2019-06-29 17:58:06
如何使用Java进行多部分/表单数据发布请求?在ApacheCommonsHttpClient的3.x版本中,提出多部分/表单数据POST请求是可能的(2004年的一个例子)。不幸的是,这在HttpClient 4.0版.对于我们的核心活动“HTTP”,MultiPart有点超出了范围。我们希望使用由其他项目维护的多部分代码,但我不知道。几年前,我们试图将多部分代码转移到Common-codec,但我没有离开那里。Oleg最近提到了另一个具有多部分解析代码的项目,它可能对我们的多部分格式代码感兴趣。我不知道目前的情况。(http:/www.nabble.com/MultiPart-form-data-in-4.0-td14224819.html)有没有人知道有哪个Java库允许我编写一个HTTP客户端,它可以发出多部分/表单数据POST请求?背景:我想使用Zoho Writer的远程API.
查看完整描述

3 回答

?
森林海

TA贡献2011条经验 获得超2个赞

这些是我的Maven依赖项。

Java代码:

HttpClient httpclient = new DefaultHttpClient();HttpPost httpPost = new HttpPost(url);FileBody uploadFilePart = new FileBody(uploadFile);MultipartEntity reqEntity = new MultipartEntity();reqEntity.addPart("upload-file", uploadFilePart);httpPost.setEntity(reqEntity);HttpResponse response = httpclient.execute(httpPost);

um.xml中的maven依赖项:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope></dependency><dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope></dependency>


查看完整回答
反对 回复 2019-06-29
?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

如果JAR的大小很重要(例如,在applet的情况下),还可以直接使用httpMIME和java.net.HttpURLConnection,而不是HttpClient。

httpclient-4.2.4:      423KBhttpmime-4.2.4:         26KBhttpcore-4.2.4:        222KBcommons-codec-1.6:     228KBcommons-logging-1.1.1:  60KBSum:                   959KBhttpmime-4.2.4:         26KBhttpcore-4.2.4:        222KBSum:                   248KB

代码:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setRequestMethod("POST");FileBody fileBody = new FileBody(new File(fileName));MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);multipartEntity.addPart("file", fileBody);connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());OutputStream out = connection.getOutputStream();try {
    multipartEntity.writeTo(out);} finally {
    out.close();}int status = connection.getResponseCode();...

依赖项在头xml中:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.2.4</version></dependency>


查看完整回答
反对 回复 2019-06-29
  • 3 回答
  • 0 关注
  • 633 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号