这篇文章给大家介绍java中HttpsPost和CloseableHttpClient如何使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
//请求json
public static String HttpsPost(String url, Map<String, Object> param) throws Exception{
String respContent ="";
String restServiceURL = url;
System.out.println(restServiceURL);
CloseableHttpClient client = HttpClients.createDefault();
//设置传入参数
StringEntity entity = new StringEntity(JSONObject.toJSONString(param), "utf-8");
HttpPost httpGet = new HttpPost(restServiceURL);
httpGet.addHeader("Content-Type","application/json;charset=UTF-8");
httpGet.setEntity(entity);
HttpResponse resp = client.execute(httpGet);
int statusCode = resp.getStatusLine().getStatusCode();
if ( 200==statusCode ) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "utf-8");
}else {
log.error("请求第三方异常,状态码{},地址{}",statusCode,url);
}
return respContent;
}
/**
* http请求 application/x-www-form-urlencoded
*/
public static String HttpsPostXw(String url, Map<String, String> param) throws Exception{
String respContent ="";
String restServiceURL = url;
CloseableHttpClient client = HttpClients.createDefault();
//设置传入参数
HttpPost httpGet = new HttpPost(restServiceURL);
httpGet.setHeader("Content-type", "application/x-www-form-urlencoded");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if(param!=null){
for (Map.Entry<String, String> entry : param.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpGet.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
//装填参数
if(param!=null){
for (Map.Entry<String, String> entry : param.entrySet()) {
httpGet.setHeader(entry.getKey(),entry.getValue());
}
}
HttpResponse resp = client.execute(httpGet);
int statusCode = resp.getStatusLine().getStatusCode();
if ( 200==statusCode ) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "utf-8");
}else {
log.error("请求第三方异常,状态码{},地址{}",statusCode,url);
}
return respContent;
}
关于java中HttpsPost和CloseableHttpClient如何使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4121470/blog/3070274