java post請求引數為檔案
阿新 • • 發佈:2022-05-19
話不多說上程式碼
import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Map; public class HttpFileUtil { /** * 以post方式呼叫第三方介面,以form-data 形式 傳送 MultipartFile 檔案資料 * @param url post請求url * @param fileParamName 檔案引數名稱 * @param multipartFile 檔案 */ public static String doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, String> paramMap) { // 建立Http例項 CloseableHttpClient httpClient = HttpClients.createDefault(); // 建立HttpPost例項 HttpPost httpPost = new HttpPost(url); // 請求引數配置 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000) .setConnectionRequestTimeout(10000).build(); httpPost.setConfig(requestConfig); try { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(StandardCharsets.UTF_8); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); String fileName = multipartFile.getOriginalFilename(); // 檔案流 builder.addBinaryBody(fileParamName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName); //表單中其他引數,如果沒有其他引數可以註釋該部分 for(Map.Entry<String, String> entry: paramMap.entrySet()) { builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8))); } HttpEntity entity = builder.build(); httpPost.setEntity(entity); // 執行提交 HttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 返回 String res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); return res; } } catch (Exception e) { e.printStackTrace(); } finally { if (httpClient != null) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } }