概述
今天在工作有一个需求需要使用后台模拟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实现的服务。
最后
以上就是健壮小丸子为你收集整理的使用apache httpcomponents 模拟html表单上传文件的全部内容,希望文章能够帮你解决使用apache httpcomponents 模拟html表单上传文件所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复