对接Content-Type="application/x-www-form-urlencoded;"的接口示例

url:调用目标接口的路径
headers:请求头属性
params:目标接口需要的入参
public static JSONObject doHttpPost(String url,Map<String, String> headers ,Map<String, String> params) {
// 创建Httpclient对象
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String resultString = "";
try {
httpClient = HttpClients.createDefault();
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("X-Gaia-Api-Key",headers.get("X-Gaia-Api-Key"));//网关key
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;");
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
log.error("HttpClientUtil/doPost,error:{}",e);
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
log.error("HttpClientUtil/close,error:{}",e);
}
}
return JSON.parseObject(resultString);
}
posted @ 2020-07-30 19:56  朱荟辰  阅读(724)  评论(0编辑  收藏  举报