/**
* post請求form表單格式發送數據
* multipart/form-data
* @param url 接口地址
* @param param 參數數組
* @return 返回結果
* @throws IOException
*/
public static String sendPost(String url, Map<String, String> param) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
String result = "";
try {
HttpPost httppost = new HttpPost(url);
//構建超時等配置信息
RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) //連接超時時間
.setConnectionRequestTimeout(1000) //從連接池中取的連接的最長時間
.setSocketTimeout(10 * 1000) //數據傳輸的超時時間
.build();
httppost.setConfig(config);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
ContentType strContent = ContentType.create("text/plain", Charset.forName("UTF-8"));
//參數填充
for (String key : param.keySet()) {
entityBuilder.addTextBody(key, param.get(key),strContent);
}
HttpEntity entity = entityBuilder.build();
httppost.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity resEntity = response.getEntity();
//回復接收
result = EntityUtils.toString(resEntity, "UTF-8");
} finally {
response.close();
}
} catch (Exception e) {
logger.error(e.getMessage());
throw e;
} finally {
httpclient.close();
}
return result;
}