public static String doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000).setSocketTimeout(6000).build();
httpPost.setConfig(requestConfig);
// 封装请求头
if (headers != null) {
Set<Map.Entry<String, String>> entrySet = headers.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
// 设置到请求头到HttpRequestBase对象中
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
// 封装请求参数
if (params != null) {
List nvps = new ArrayList<>();
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 设置到请求的http对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, “UTF-8”));
}
// 创建httpResponse对象
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
try {
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = “”;
if (httpResponse.getEntity() != null) {
content = EntityUtils.toString(httpResponse.getEntity(), “UTF-8”);
}
return content;
}
} finally {
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}
return null;
}
doPost封装
最新推荐文章于 2023-05-26 22:30:35 发布