今天學習使用了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) { } } }此段代碼所需依賴包下載地址(免積分的):http://download.csdn.net/detail/coding13/9772027
新聞熱點
疑難解答