1.客户端代码如下:
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class ClientMultipartFormPost {
public static void main(String[] args){
new ClientMultipartFormPost().initClass();
}
public void initClass(){
//1:创建一个httpclient对象
HttpClient httpclient = new DefaultHttpClient();
Charset charset = Charset.forName("UTF-8");//设置编码
try {
//2:创建http的发送方式对象,是GET还是post
HttpPost httppost = new HttpPost("http://localhost:8080/myhome/mypage/upOutRentHourse.do");
//3:创建要发送的实体,就是key-value的这种结构,借助于这个类,可以实现文件和参数同时上传,很简单的。
MultipartEntity reqEntity = new MultipartEntity();
FileBody bin = new FileBody(new File("C:/Users/kin.liufu.2GOTECH/Desktop/资料/Go.XML Message Protocol Specification (V2.88h).doc"));
FileBody bin1 = new FileBody(new File("C:/Users/kin.liufu.2GOTECH/Desktop/资料/Go.XML Message Protocol Specification (V2.88h).doc"));
StringBody comment = new StringBody("房子类型为三房一厅",charset);
ArrayList<FileBody> fileBodys = new ArrayList<>();
fileBodys.add(bin);
fileBodys.add(bin1);
addFileBodyPart("upLoadImage", fileBodys, reqEntity);
reqEntity.addPart("typeOfHourseRoom", comment);
httppost.setEntity(reqEntity);
//4:执行httppost对象,从而获得信息
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
//获得返回来的信息,转化为字符串string
String resString = EntityUtils.toString(resEntity);
System.out.println(resString);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
}
}
//当多个文件需要上传时,对文件进行组装
public void addFileBodyPart(String paramName, ArrayList<FileBody> fileBodys, MultipartEntity reqEntity){
if(fileBodys == null || fileBodys.size() < 1 || reqEntity == null || paramName == null){
return;
}
for(FileBody iteam : fileBodys){
reqEntity.addPart(paramName,iteam);
}
}
}
2.服务器端的代码
package com.myhome.base.controller;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import com.myhome.base.entity.RentHourse;
import com.myhome.base.entity.User;
import com.myhome.base.enums.TypeOfRentHourse;
import com.myhome.base.service.RentHourseService;
import com.myhome.base.service.UserService;
import com.myhome.core.system.InitData;
import com.myhome.core.util.Utility;
/**
* <p>创建时间: 2016年4月4日</p>
* @author kin.liufu
* @describe 租房控制器
*/
@Scope("prototype")
@RequestMapping("/mypage/")
@Controller
public class RentHourseController {
@Resource
private RentHourseService rentHourseService;
@Resource
private UserService userService;
/**
* @describe此方法接口给用户提供发布房子的信息
*/
@RequestMapping(produces = "text/html;charset=UTF-8", value = "upOutRentHourse")
@ResponseBody
public String upOutRentHourse(HttpServletRequest request, String typeOfHourseRoom, String typeofHourse, String typeOfPay, String rentPay, String phoneNum, String describe , @RequestParam("upLoadImage") MultipartFile[] upLoadImage){
String ERRTIP = "";
HashMap<String, String> hashMap = new HashMap<>();
if(request.getSession().getAttribute("USERINFO") == null){
ERRTIP = "TIMEOUTOFLOGIN";
hashMap.put("ERRTIP", ERRTIP);
}else if(Utility.isStringEmpty(typeOfHourseRoom) || Utility.isStringEmpty(describe) || Utility.isStringEmpty(phoneNum) || Utility.isStringEmpty(rentPay)){
ERRTIP = "传过来的信息有空";
hashMap.put("ERRTIP", ERRTIP);
}else{
String relativePath = "";
RentHourse rentHourse = new RentHourse();
MultipartFile multipartFile = null;
if(upLoadImage != null && upLoadImage.length > 0){
String rentHoursePath = "";
for(int i=0; i<upLoadImage.length && i <= 7; i++){
multipartFile = upLoadImage[i];
String fileName = multipartFile.getOriginalFilename();
if(!Utility.isStringEmpty(fileName)){
relativePath = Utility.formatDateToString(new Date(), "YYYY-MM-dd") + "/" + System.currentTimeMillis() + "~" + (int)(Math.random()*100) + Utility.getTypeOfFile(fileName);
File targetFile = new File(InitData.outPutPath, "USER/Imges/rentHourseImages/" + relativePath);
if(!targetFile.exists()){
targetFile.mkdirs();
//保存
try {
multipartFile.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
}
if(Utility.isStringEmpty(rentHoursePath)){
rentHoursePath += relativePath;
}else{
rentHoursePath += "&&" + relativePath;
}
}
}
rentHourse.setImagePath(rentHoursePath);
}
if("oneroom".equals(typeOfHourseRoom)){
rentHourse.setTypeOfRentHourse(TypeOfRentHourse.ONEROOM);
}else if("tworoom".equals(typeOfHourseRoom)){
rentHourse.setTypeOfRentHourse(TypeOfRentHourse.TWOROOM);
}else if("threeroom".equals(typeOfHourseRoom)){
rentHourse.setTypeOfRentHourse(TypeOfRentHourse.THREEROOM);
}else if("fourroom".equals(typeOfHourseRoom)){
rentHourse.setTypeOfRentHourse(TypeOfRentHourse.FOURROOM);
}else if("morefourroom".equals(typeOfHourseRoom)){
rentHourse.setTypeOfRentHourse(TypeOfRentHourse.MOREFOURROOM);
}
User user = (User) request.getSession().getAttribute("USERINFO");
rentHourse.setUser(user);
rentHourse.setTypeofHourse(typeofHourse);
rentHourse.setUserName(user.getName());
rentHourse.setPayfor(Float.valueOf(rentPay));
rentHourse.setPhoneNum(phoneNum);
rentHourse.setDescribe(describe);
rentHourse.setTypeOfPay(typeOfPay);
if(!rentHourseService.save(rentHourse)){
ERRTIP = "房子发布的时候,保存到数据库时,出现了错误";
hashMap.put("ERRTIP", ERRTIP);
}
}
return JSONObject.toJSONString(hashMap);
}
}
总结:httpclient的请求需要依赖httpmime-4.2.jar、httpclient-4.2.jar、commons-logging-1.1.1.jar、httpcore-4.2.jar
每个包提供的功能如下:
1.httpmime-4.2.jar提供FileBody、StringBody和MultipartEntity
2.httpclient-4.2.jar提供httpclient最主要的功能,比如:HttpClient、HttpPost等。
3.commons-logging-1.1.1.jar提供日志打印功能,也是不能少的
4.httpcore-4.2.jar提供一些供httpclient使用的核心接口