HttpClient以multipart/form-data上傳檔案
阿新 • • 發佈:2019-01-09
封裝的方法:
呼叫postMultipartpublic static String postFileMultiPart(String url,Map<String,ContentBody> reqParam) throws ClientProtocolException, IOException{ CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 建立httpget. HttpPost httppost = new HttpPost(url); //setConnectTimeout:設定連線超時時間,單位毫秒。setConnectionRequestTimeout:設定從connect Manager獲取Connection 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連線池的。setSocketTimeout:請求獲取資料的超時時間,單位毫秒。 如果訪問一個介面,多少時間內無法返回資料,就直接放棄此次呼叫。 RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build(); httppost.setConfig(defaultRequestConfig); System.out.println("executing request " + httppost.getURI()); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); for(Entry<String,ContentBody> param : reqParam.entrySet()){ multipartEntityBuilder.addPart(param.getKey(), param.getValue()); } HttpEntity reqEntity = multipartEntityBuilder.build(); httppost.setEntity(reqEntity); // 執行post請求. CloseableHttpResponse response = httpclient.execute(httppost); System.out.println("got response"); try { // 獲取響應實體 HttpEntity entity = response.getEntity(); //System.out.println("--------------------------------------"); // 列印響應狀態 //System.out.println(response.getStatusLine()); if (entity != null) { return EntityUtils.toString(entity,Charset.forName("UTF-8")); } //System.out.println("------------------------------------"); } finally { response.close(); } } finally { // 關閉連線,釋放資源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
利用httpclient上傳檔案需要兩點:String url = "xxxxxxx"; String httpRes = null; String localFileName = "E:/2.jpg"; Map<String,ContentBody> reqParam = new HashMap<String,ContentBody>(); reqParam.put("Filename", new StringBody(localFileName, ContentType.MULTIPART_FORM_DATA)); reqParam.put("pictitle", new StringBody(localFileName, ContentType.MULTIPART_FORM_DATA)); reqParam.put("dir", new StringBody("upload1", ContentType.MULTIPART_FORM_DATA)); reqParam.put("fileNameFormat", new StringBody("{time}{rand:6}", ContentType.MULTIPART_FORM_DATA)); reqParam.put("fileName", new StringBody(localFileName, ContentType.MULTIPART_FORM_DATA)); reqParam.put("fileName", new StringBody(localFileName, ContentType.MULTIPART_FORM_DATA)); reqParam.put("upfile", new FileBody(new File(fileLocation))); reqParam.put("Upload", new StringBody("Submit Query", ContentType.MULTIPART_FORM_DATA)); httpRes = HttpClientUtil.postFileMultiPart(url,reqParam);