---
title: "使用apache httpcomponents 模拟html表单上传文件"
author: "泪雨的终结"
date: "2014-11-07T23:41:57Z"
tags: []
categories: ["编程语言"]
slug: "apache-httpcomponents-html"
draft: false
lastmod: "2014-11-07T23:41:23Z"
id: 2153595
url: "https://eof.iteye.com/blog/2153595"
---

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

```xml

<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，该类能够很好的支持多文件的上传。简单实现代码如下：

```java
	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实现的服务。