/*
* url : 第3方接口地址
* params :参数
*/
public static String HttpClientConnection(String url, Map<String,String> params) {
// 创建Httpclient对象
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String resultString = "";
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
List<org.apache.http.NameValuePair> paramList = new ArrayList<org.apache.http.NameValuePair>();
for(Map.Entry<String, String> entry : params.entrySet()){
paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 参数设置
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,Consts.UTF_8);
httpPost.setEntity(entity);
httpPost.setHeader("Access-Control-Allow-Origin","*");
httpClient = HttpClients.createDefault();
try {
// 执行http请求
response = httpClient.execute(httpPost);
resultString =EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
} finally {
try {
if(response !=null)
response.close();
} catch (IOException e) {
}
try {
if(httpClient !=null)
httpClient.close();
} catch (IOException e) {
}
}
return resultString;
}
Java HttpPost 调用第3方接口实例方法
最新推荐文章于 2024-06-22 21:33:16 发布