使用HttpClient傳送HttpPost請求包含上傳本地圖片和遠端圖片的傳輸實現
阿新 • • 發佈:2019-01-08
在實際專案中需要在當前系統中模擬瀏覽器傳送一個post請求,正常情況下傳文字沒多大問題,但是如果帶上傳檔案功能的話,
網上的資料不太好找,好在經過我多方尋找,加上自由發揮,真讓我搞出來了。
下面程式碼為核心程式碼,
可以上傳
File物件,
轉換成byte陣列型別(String型別Base64編碼的資訊的圖片)
String型別 的資料,
滿足了,傳送post請求大部分上傳需要,每一步都有詳細說明,並且都有log打出。希望能幫到需要的人。
專案程式碼在下面,實現作為參考
專案程式碼地址
public class HttpTest { public String start(String path,String base64String,String imageFilePath) throws ClientProtocolException, IOException{ // 1. 建立上傳需要的元素型別 // 1.1 裝載本地上傳圖片的檔案 File imageFile = new File(imageFilePath); FileBody imageFileBody = new FileBody(imageFile); // 1.2 裝載經過base64編碼的圖片的資料 String imageBase64Data = base64String; ByteArrayBody byteArrayBody = null; if(StringUtils.isNotEmpty(imageBase64Data)){ byte[] byteImage = Base64.decodeBase64(imageBase64Data); byteArrayBody = new ByteArrayBody(byteImage,"image_name"); } // 1.3 裝載上傳字串的物件 StringBody name = new StringBody("admin",ContentType.TEXT_PLAIN); System.out.println("裝載資料完成"); // 2. 將所有需要上傳元素打包成HttpEntity物件 HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("name", name) .addPart("file1",imageFileBody) .addPart("file2",byteArrayBody).build(); System.out.println("打包資料完成"); // 3. 建立HttpPost物件,用於包含資訊傳送post訊息 HttpPost httpPost = new HttpPost(path); httpPost.setEntity(reqEntity); System.out.println("建立post請求並裝載好打包資料"); // 4. 建立HttpClient物件,傳入httpPost執行傳送網路請求的動作 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost); System.out.println("傳送post請求並獲取結果"); // 5. 獲取返回的實體內容物件並解析內容 HttpEntity resultEntity = response.getEntity(); String responseMessage = ""; try{ System.out.println("開始解析結果"); if(resultEntity!=null){ InputStream is = resultEntity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuffer sb = new StringBuffer(); String line = ""; while((line = br.readLine()) != null){ sb.append(line); } responseMessage = sb.toString(); System.out.println("解析完成,解析內容為"+ responseMessage); } EntityUtils.consume(resultEntity); }finally{ if (null != response){ response.close(); } } return responseMessage; } public static void main(String[] args) throws ClientProtocolException, IOException { HttpTest ht = new HttpTest(); ht.start("http//127.0.0.1:8080/test/uplod/upload.do","dfsdfsdfsdf","C:\\Intel\\test.jpg"); } }