前言
對接某公司的介面,涉及到資質上傳等業務,需要對接他們的上傳附件介面,
JDK1.8 httpclient 4.x
封裝httpclient方法
public static String postFileMultiPart(String url,Map<String, ContentBody> reqParam) throws IOException{
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 創建http
HttpPost httppost = new HttpPost(url);
//setConnectTimeout:設定連接超時時間,單位毫秒,setConnectionRequestTimeout:設定從connect Manager獲取Connection 超時時間,單位毫秒,
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
httppost.setConfig(defaultRequestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for(Map.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();
if (entity != null) {
return EntityUtils.toString(entity, Charset.forName("UTF-8"));
}
} finally {
response.close();
}
} finally {
// 關閉連接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
因為我方系統需要給前端提供上傳介面 使用的MultipartFile來接收檔案
所以這邊需要MultipartFile轉下File檔案
public static File transferToFile(MultipartFile multipartFile) {
//選擇用緩沖區來實作這個轉換即使用java 創建的臨時檔案 使用 MultipartFile.transferto()方法 ,
File file = null;
try {
String originalFilename = multipartFile.getOriginalFilename();
//獲取檔案后綴
String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
file = File.createTempFile(originalFilename, prefix);
multipartFile.transferTo(file);
//洗掉臨時檔案
file.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
方法呼叫
public RestResponse attachment(MultipartFile file) throws Exception {
Map<String, ContentBody> reqParam = new HashMap<>();
//普通型別
reqParam.put("appId", new StringBody("appid", ContentType.MULTIPART_FORM_DATA));
//檔案
reqParam.put("file", new FileBody(FileUploadUtils.transferToFile(file), ContentType.IMAGE_JPEG));
String result = HttpClientUtil.postFileMultiPart("http://www.com/attachment", reqParam);
}
后記
一頓操作對接完事,肯定有朋友問 為什么不讓前端兄弟直接對接呢,因為對接的介面有權限校驗,前端直接調會有泄漏token和秘鑰的風險,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/553059.html
標籤:其他
下一篇:返回列表
