1、doGet
String doGet(String url) throws Exception{
// 创建 HttpClient 对象
HttpClient client = HttpClientBuilder.create().build();
// 实例化 HttpGet 对象,准备发送 get 请求
HttpGet request = new HttpGet(url);
WeChatApiUtil.send(appKey,"请求地址:"+url);
// 发送 get 请求,并获取结果信息于 response 中
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity());
return strResult;
}else{
throw new Exception("调用接口失败,错误代码"+response.getStatusLine().getStatusCode()+",请求地址:"+url);
}
}
2、doPost
String doPost(String url,TreeMap<String,Object> params) throws Exception{
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http POST请求
HttpPost httpPost = new HttpPost(url);
// 准备 CloseableHttpResponse 对象用于存放结果信息
CloseableHttpResponse response = null;
// 设置post请求参数
JSONObject param = new JSONObject();
for (String key : params.keySet()) {
param.put(key,params.get(key));
}
// 将封装好的请求参数转换成 json 字符串
StringEntity s = new StringEntity(param.toJSONString(1),"UTF-8");
// s.setContentEncoding("UTF-8");
// s.setContentType("application/json;charset=utf-8");//发送json数据需要设置contentType
httpPost.setEntity(s);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
System.out.println(s);
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 解析响应体
String content = EntityUtils.toString(response.getEntity());
if (response != null) {
response.close();
}
httpclient.close();
return content;
}else{
throw new Exception("调用接口失败,错误代码"+response.getStatusLine().getStatusCode()+",请求地址:"+url);
}
}