HttpClient以multipart/form-data上傳檔案
阿新 • • 發佈:2020-09-15
public static String doPostUpload(String url, Map<String, ContentBody> mapParam, String headers) { // 建立請求連線,新增Cookie CloseableHttpClient closeableHttpClient = null; CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie( "JSESSIONID", JSESSIONID ); cookie.setVersion( Version ); cookie.setDomain( Domain ); cookie.setPath( Path ); cookieStore.addCookie( cookie ); closeableHttpClient = HttpClients.custom() .setProxy( proxy ) .setRedirectStrategy( new LaxRedirectStrategy() ) //自動跟隨重定向 .setConnectionTimeToLive( 6000, TimeUnit.MILLISECONDS ) .setDefaultCookieStore( cookieStore ) .build(); HttpPost httpPost = new HttpPost( url ); System.out.println( "請求地址 " + httpPost.getURI() ); //setConnectTimeout:設定連線超時時間,單位毫秒。 // setConnectionRequestTimeout:設定從connect Manager獲取Connection 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連線池的。 // setSocketTimeout:請求獲取資料的超時時間,單位毫秒。 如果訪問一個介面,多少時間內無法返回資料,就直接放棄此次呼叫。 RequestConfig defaultRequestConfig = RequestConfig.custom(). setConnectTimeout( 5000 ) .setConnectionRequestTimeout( 5000 ) .setSocketTimeout( 15000 ) .build(); httpPost.setConfig( defaultRequestConfig ); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); for (Map.Entry<String, ContentBody> param : mapParam.entrySet()) { multipartEntityBuilder.addPart( param.getKey(), param.getValue() ); } //multipartEntityBuilder.setCharset( Charset.forName( "utf-8" )); multipartEntityBuilder.setMode( HttpMultipartMode.BROWSER_COMPATIBLE ); //加上此行程式碼解決返回中文亂碼問題 HttpEntity reqEntity = multipartEntityBuilder.build(); httpPost.setEntity( reqEntity ); // 處理頭部資訊 if (!CommonMethord.isEmpty( headers )) { String[] header_array = headers.split( ";" ); for (String line : header_array) { String[] header = line.split( "=" ); httpPost.addHeader( header[0], header[1] ); } } // 獲取返回物件 String result = ""; // CloseableHttpResponse resp = null; //返回結果 try { // 傳送請求 resp = closeableHttpClient.execute( httpPost ); // http 狀態 200 404 302 500 StatusLine line = resp.getStatusLine(); System.out.println( "返回響應碼: " + line ); // 結果 HttpEntity httpEntity = resp.getEntity(); if (httpEntity != null) { result = EntityUtils.toString( httpEntity, Charset.forName( "UTF-8" ) ); System.out.println( "返回結果: " + result ); } } catch (Exception e) { e.printStackTrace(); } finally { try { // 關閉連線 closeableHttpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
// 測試程式碼