今天在工作有一个需求需要使用后台模拟html表单上传文件,想到使用apache-httpcomponents来处理。主要使用的包有
模拟content-type为multipart-form主要使用的类是MultipartEntity,该类能够很好的支持多文件的上传。简单实现代码如下:
然后再配上HttpPost 和 DefaulHttpClient 即可完成模拟表单的上传。
工程中不仅包含httpclient的上传,还包含页面表单的上传和后台用commons-fileupload实现的服务。
<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 HttpClient组件模拟HTML表单上传文件,包括依赖配置与关键代码实现。此外,还涉及了页面表单上传及后台使用commons-fileupload进行处理的方法。
880

被折叠的 条评论
为什么被折叠?



