使用apache httpcomponents 模拟html表单上传文件

今天在工作有一个需求需要使用后台模拟html表单上传文件,想到使用apache-httpcomponents来处理。主要使用的包有

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

模拟content-type为multipart-form主要使用的类是MultipartEntity,该类能够很好的支持多文件的上传。简单实现代码如下:
	private static MultipartEntity getMultipartEntity() {
String file1 = FileUploadHttpclient.class.getResource("sampleUploadFile1.txt").getFile();
String file2 = FileUploadHttpclient.class.getResource("sampleUploadFile2.txt").getFile();

MultipartEntity multipartEntity = new MultipartEntity();
//后台接收什么就添加什么
multipartEntity.addPart("text1", StringBody.create("this is httpclient"));
multipartEntity.addPart("file1", new FileBody(new File(file1)));
multipartEntity.addPart("file2", new FileBody(new File(file2)));
return multipartEntity;
}

然后再配上HttpPost 和 DefaulHttpClient 即可完成模拟表单的上传。

工程中不仅包含httpclient的上传,还包含页面表单的上传和后台用commons-fileupload实现的服务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值