1. 程式人生 > >使用HttpClient4實現檔案上傳請求的傳送,伺服器端以MultipartFile形式接收(附依賴jar包地址)

使用HttpClient4實現檔案上傳請求的傳送,伺服器端以MultipartFile形式接收(附依賴jar包地址)

今天學習使用了HttpClient4.2向服務端傳送上傳檔案的post請求,由於伺服器端採用MultipartFile形式接收,查詢資料後決定使用HttpClient4.2實現,以下是實現程式碼(僅作測試使用):

   public void testtaskPost()throws  Exception{
        HttpClient httpclient = new DefaultHttpClient();
        try {
            //新建一個httpclient Post 請求
            HttpPost httppost = new 
            HttpPost("http://127.0.0.1:8889/taskmanagement/task"
); //由於只是測試使用 這裡的路徑對應本地檔案的物理路徑 FileBody bin = new FileBody(new File("E://2017//1.doc")); File myfile = new File("E://2017//1.doc"); long size = myfile.length(); //向MultipartEntity新增必要的資料 StringBody comment = new StringBody("1.doc", Charset.forName
("UTF-8")); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file",bin);//file為請求後臺的Fileupload引數 reqEntity.addPart("filename",comment);//請求後臺Fileupload的引數 httppost.setEntity(reqEntity); //這裡是後臺接收檔案的介面需要的引數,根據介面文件需要放在http請求的請求頭 String taskid ="919894d9-ea5a-4f6a-8edd-b14ef3b6f104"
; httppost.setHeader("task-id",taskid); String fileid = UUID.randomUUID().toString(); httppost.setHeader("file-id",fileid); httppost.setHeader("file-name","1.doc"); httppost.setHeader("file-size",String.valueOf(size)); httppost.setHeader("total", String.valueOf(1)); httppost.setHeader("index",String.valueOf(1)); HttpResponse response = httpclient.execute(httppost); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == HttpStatus.SC_OK){ System.out.println("伺服器正常響應....."); HttpEntity resEntity = response.getEntity(); System.out.println( //httpclient自帶的工具類讀取返回資料 EntityUtils.toString(resEntity)); System.out.println( resEntity.getContent()); EntityUtils.consume( resEntity); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }