1. 程式人生 > >Java客戶端利用httpclient來同時上傳檔案和其他字串引數

Java客戶端利用httpclient來同時上傳檔案和其他字串引數

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使用的核心介面