本人使用 httpclient 進行接口測試的過程當中,遇到了上傳文件的接口,以前的文章已經完成了二進制流上傳圖片的代碼,可是尚未封裝成固定的使用方法,今天分享一下封裝後的方法,供你們參考。java
/** * 設置二進制流實體,params 裏面參數值爲 file * * @param httpPost * httpPsot 請求 * @param params * 請求參數 * @param file * 文件 */ public void setMultipartEntityEntity(HttpPost httpPost, JSONObject params, File file) { String fileName = getFileName(file); InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } Iterator<String> keys = params.keys();// 遍歷 params 參數和值 MultipartEntityBuilder builder = MultipartEntityBuilder.create();// 新建builder對象 while (keys.hasNext()) { String key = keys.next(); String value = params.getString(key); if (value.equals("file")) { builder.addBinaryBody(key, inputStream, ContentType.create("multipart/form-data"), fileName);// 設置流參數 } else { StringBody body = new StringBody(value, ContentType.create("text/plain", Consts.UTF_8));// 設置普通參數 builder.addPart(key, body); } } HttpEntity entity = builder.build();// 生成entity httpPost.setEntity(entity);// 設置 entity }
此方法僅針對 Linux 系統,由於 Windows 系統在文件路徑中用的「\」,在代碼裏是「\」因此 Windows 系統的朋友得注意力。python