使用HttpClient实现消息推送

推送功能-核心实现接口:

  public static String sendMsg(String appid, String title, String content) {
            // 1. 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            Map 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";
    }

你可能感兴趣的:(J2SE,java,网络)