Java 中使用 HttpClient 4.3.6 进行文件上传

代码部分#

Copy
import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class SimpleTest { @Test public void fileUpload() { String url = "http://site.com/api"; CloseableHttpClient httpClient = HttpClients.createDefault(); try { // 发送二进制数据(文件) MultipartEntityBuilder builder = MultipartEntityBuilder.create(); File f = new File("/Path/of/your/file"); builder.addBinaryBody( "file", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM, f.getName() ); // 发送文本数据 builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN ); HttpEntity multipart = builder.build(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(httpPost); System.out.println(EntityUtils.toString(response.getEntity())); } catch (IOException e) { e.printStackTrace(); } } }

Maven 依赖#

Copy
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.6</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.3.6</version> <scope>compile</scope> </dependency>
posted @   质子  阅读(486)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示
CONTENTS