HttpClient请求Demo
2018-10-08 本文已影响0人
柴建龙
public static String postDemo(String url,Map<String,String> map,String encoding){
String body="";
//1、创建HttpClient对象
CloseableHttpClient httpClient= HttpClients.createDefault();
HttpClientUtil httpClientUtil=new HttpClientUtil();
//2、创建请求方法对象
HttpPost post= (HttpPost) httpClientUtil.getRequest(url,HttpMethods.POST);
List<NameValuePair> list=new ArrayList<>();
if(map!=null){
for(Map.Entry<String,String> entry:map.entrySet()){
list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
}
try {
//3、设置参数到请求方法对象中
post.setEntity(new UrlEncodedFormEntity(list,encoding));
Log.info("请求url:"+url);
Log.info("请求参数:"+list.toString());
try {
//4、执行请求
CloseableHttpResponse response=httpClient.execute(post);
//5、获取结果实体
HttpEntity entity=response.getEntity();
if(entity!=null){
//6、将结果实体转换为字符串
body= EntityUtils.toString(entity,encoding);
}
EntityUtils.consume(entity);
//7、释放连接
response.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return body;
}