实现以form-data参数发送post请求
/**
* 以post方式调用第三方接口,以form-data 形式 发送数据
*
* @param url post请求url
* @param paramMap 表单里其他参数
* @return
*/
public static String doPost(String url, Map<String, String> paramMap) {
// 创建Http实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//表单中参数
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(), java.nio.charset.Charset.forName("UTF-8"));
return res;
}
} catch (Exception e) {
e.printStackTrace();
logger.error("调用HttpPost失败!" + e.toString());
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
logger.error("关闭HttpPost连接失败!");
}
}
}
return null;
}