在对接一个第三方接口的时候,发现 请求参数Body要以multipart/form-data 方式提交。然后就去收集了一下资料,特此记录一下
/**
* 以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;
}
然后放一下我使用的依赖
<!-- httpclient 相关依赖-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
然后如果使用PostMan以这种方式测试的话,是这样的。
参考:https://blog.csdn.net/LYY1448019681/article/details/115124407