推送功能-核心实现接口:
public static String sendMsg(String appid, String title, String content) {
// 1. 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
Map<String, Object> param = new HashMap<>();
param.put("cids",appid);
param.put("title",title);
param.put("content",content);
JSONObject json = new JSONObject(param);
// 2.创建HttpPost对象并指定请求URL。
HttpPost httpPost = new HttpPost("https://*****.com/msg-push");
// 3. 创建请求内容,调用setEntity(HttpEntity entity)方法来设置请求参数
StringEntity entity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 4.发送http请求:execute(HttpUriRequest request)发送请求
response = httpClient .execute(httpPost);
// 5.调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
Map fastjson = (Map) JSON.parse(resultString);
return (String)fastjson.get("errMsg");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 6.释放连接。无论执行方法是否成功,都必须释放连接
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "error";
}
总结
使用HttpClient发送请求、接收响应,一般需要如下步骤:
- 创建HttpClient对象。帮助我们执行请求的对象
- 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。请求方式
- 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。封装传参
- 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。执行拿到结果
- 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。获取相关信息
- 释放连接。无论执行方法是否成功,都必须释放连接 释放连接