/*
* 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-07-07 03:58:45 发布
本文提供了一个使用Java实现的HTTP客户端连接示例,通过HttpPost发送POST请求到指定URL,并附带参数。示例展示了如何创建参数列表、设置请求头及执行HTTP请求。


3054

被折叠的 条评论
为什么被折叠?



