/**
* Project Name:testHttpClient
* File Name:ClientMultipartFormPost.java
* Package Name:com.test.httpclient
* Date:2016年12月28日下午4:01:59
* Copyright (c) 2016, 77493077@qq.com All Rights Reserved.
*
*/
package com.test.httpclient;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.http.Consts;
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.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* ClassName:ClientMultipartFormPost <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 2016年12月28日 下午4:01:59 <br/>
* @author ZengZhuo(lenovo)
* @version
* @since JDK 1.8+
* @see
*/
public class ClientMultipartFormPost {
/**
* 这个例子展示了如何执行请求包含一个多部分编码的实体
* 模拟表单提交
* @throws IOException
*/
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
//要上传的文件的路径
String filePath = "D:\\mail.jpeg";
//把一个普通参数和文件上传给下面这个地址 是一个servlet
HttpPost httpPost = new HttpPost("http://localhost:8080/UploadServlet");
//把文件转换成流对象FileBody
FileBody bin = new FileBody(new File(filePath));
//普通字段 重新设置了编码方式
StringBody comment = new StringBody("这里是一个评论", ContentType.create("text/plain", Consts.UTF_8));
//StringBody comment = new StringBody("这里是一个评论", ContentType.TEXT_PLAIN);
StringBody name = new StringBody("王五", ContentType.create("text/plain", Consts.UTF_8));
StringBody password = new StringBody("123456", ContentType.create("text/plain", Consts.UTF_8));
HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("media", bin)//相当于<input type="file" name="media"/>
.addPart("comment", comment)
.addPart("name", name)//相当于<input type="text" name="name" value=name>
.addPart("password", password)
.addTextBody("value", "roy")
.build();
httpPost.setEntity(reqEntity);
System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
//发起请求 并返回请求的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
System.out.println("----------------------------------------");
//打印响应状态
System.out.println(response.getStatusLine());
//获取响应对象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
//打印响应长度
System.out.println("Response content length: " + resEntity.getContentLength());
//打印响应内容
System.out.println(EntityUtils.toString(resEntity,Charset.forName("UTF-8")));
}
//销毁
EntityUtils.consume(resEntity);
} finally {
response.close();
}
}finally{
httpClient.close();
}
}
}
package com.test.httpclient;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
*/
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public UploadServlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//利用apache的common-upload上传组件来进行 来解析获取到的流文件
//把上传来的文件放在这里
String uploadPath = getServletContext().getRealPath("/upload");//获取文件路径
//检测是不是存在上传文件
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
//指定在内存中缓存数据大小,单位为byte,这里设为1Mb
factory.setSizeThreshold(1024*1024);
//设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
factory.setRepository(new File("D://temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// 指定单个上传文件的最大尺寸,单位:字节,这里设为5Mb
upload.setFileSizeMax(5 * 1024 * 1024);
//指定一次上传多个文件的总尺寸,单位:字节,这里设为10Mb
upload.setSizeMax(10 * 1024 * 1024);
upload.setHeaderEncoding("UTF-8"); //设置编码,因为我的jsp页面的编码是utf-8的
List<FileItem> items = null;
try {
// 解析request请求
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
if(items!=null){
//把上传文件放到服务器的这个目录下
if (!new File(uploadPath).isDirectory()){
new File(uploadPath).mkdirs(); //选定上传的目录此处为当前目录,没有则创建
}
//解析表单项目
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
//如果是普通表单属性
if (item.isFormField()) {
//<input type="text" name="content">
String name = item.getFieldName();//相当于input的name属性
String value = item.getString();//input的value属性
System.out.println("属性:"+name+" 属性值:"+value);
}
//如果是上传文件
else {
//属性名
String fieldName = item.getFieldName();
//上传文件路径
String fileName = item.getName();
fileName = fileName.substring(fileName.lastIndexOf("/")+1);// 获得上传文件的文件名
try {
item.write(new File(uploadPath,fileName));
} catch (Exception e) {
e.printStackTrace();
}
//给请求页面返回响应
response.getWriter().println("文件上传成功! 文件名是:"+fileName);
}
}
}
}
}
public static void main(String[] args) {
String name ="aaa";
String [] values = new String[]{"123"};
Map<String,String[]> ms = new HashMap<String,String[]>();
ms.put(name, values);
System.out.println(ms.toString());
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Systemmonitor</groupId>
<artifactId>Systemmonitor</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name/>
<description/>
<dependencies>
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>javaee-api</artifactId>
<version>5.0-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>1.2_04</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>1.2_04</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.1.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.1.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.1.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src</sourceDirectory>
<outputDirectory>${basedir}/WebRoot/WEB-INF/classes</outputDirectory>
<resources>
<resource>
<directory>${basedir}/src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webappDirectory>${basedir}/WebRoot</webappDirectory>
<warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
</project>