java推送企业微信消息

所需jar包 --创建请求用

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.8</version>
        </dependency>

所需配置

cropId: 企业微信id

corpsecret 应用的凭证密钥

agentid 企业应用的id

1、封装消息体



//封装消息体   可以直接用json也可以创建对象
public void send(String msg, String userIds) {
 //1.创建文本消息对象
        TextMessage message = new TextMessage();
        message.setTouser(userIds);
        //1.2必需
        message.setMsgtype("text");
        message.setAgentid(agentId);

        Text text = new Text();
        text.setContent(msg);
        message.setText(text);
        sendMessage(0, message);
}

@Data
public class TextMessage extends BaseMessage {
    /**
     * 文本TextMessage
     */
    private Text text;
    /**
     * 表示是否是保密消息,0表示否,1表示是,默认0
     */
    private int safe;
}

@Data
public class Text {
    /**
     * 消息内容,最长不超过2048个字节
     */
    private String content;
}

2.请求token及推送消息

public void sendMessage(Integer mark, BaseMessage message) {


               String key = "wx_accessToken:" + platformVO.getAppId() + "_secret:" + platformVO.getSecret();
        String token = null;
        token = redisTemplate.opsForValue().get(key);

        //mark大于0代表token失效
        if (null == token || mark > 0) {
            log.info("获取token");
            //2.获取access_token:根据企业id和通讯录密钥获取access_token,并拼接请求url
            AccessToken accessToken = WeiXinUtil.getAccessToken(platformVO.getAppId(), platformVO.getSecret());
            token = accessToken.getToken();
            redisTemplate.opsForValue().set(key, accessToken.getToken(), accessToken.getExpiresIn() - 4, TimeUnit.SECONDS);
        }
        log.info("企业微信token:" + token);

        //3.发送消息:调用业务类,发送消息
        String jsonMessage = JSONObject.toJSONString(message);

        //2.获取请求的url
        String sendMessage_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token;

        //3.调用接口,发送消息
        String result = HttpUtil.doPost(sendMessage_url, null, jsonMessage, null);
        JSONObject jsonObject = JSONObject.parseObject(result, JSONObject.class);
        List<String> errorCode = Lists.newArrayList();
        errorCode.add("40014");
        errorCode.add("42001");
        //4.错误消息处理
        if (null != jsonObject) {
            if (errorCode.contains(jsonObject.getString("errcode")) && mark < 3) {
                log.info("消息推送失败 errcode:{}", jsonObject.getInteger("errcode") + "重新获取token");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sendMessage(mark + 1, message);
            } else if (0 != jsonObject.getInteger("errcode")) {
                log.error("消息推送失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            } else {
                log.info("企业微信消息推送成功!");
            }
        }
    }
/**
 * 所需要用到的工具类
 * @author tangh
 */
@Slf4j
public class WeiXinUtil {
    /**
     * 微信的请求url
     * 获取access_token的接口地址(GET) 限200(次/天)
     */
    public final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpsecret}";


    /**
     * 1.发起https请求并获取结果
     *
     * @param requestUrl 请求地址
     * @param outputStr  提交的数据
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
    public static JSONObject httpRequest(String requestUrl, String outputStr) {
        JSONObject jsonObject = null;
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(requestUrl);
            StringEntity requestEntity = new StringEntity(outputStr, "utf-8");
            httpPost.setEntity(requestEntity);
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            response = httpClient.execute(httpPost);

            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            jsonObject = JSONObject.parseObject(result);
        } catch (ConnectException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("POST请求response关闭异常,错误信息为{}", e.getMessage(), e);
            }
        }
        return jsonObject;
    }

    /**
     * 发起http请求获取返回结果
     *
     * @param requestUrl 请求地址
     * @return
     */
    public static String httpRequest(String requestUrl) {
        String result = null;
        HttpGet httpGet = new HttpGet(requestUrl);
        CloseableHttpResponse response = null;
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            response = httpClient.execute(httpGet);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.error("GET请求response关闭异常,错误信息为{}", e.getMessage(), e);
            }
        }

        return result;
    }

    /**
     * 3.获取access_token
     *
     * @param appid     凭证
     * @param appsecret 密钥
     * @return
     */
    public static AccessToken getAccessToken(String appid, String appsecret) {
        AccessToken accessToken = null;

        String requestUrl = ACCESS_TOKEN_URL.replace("{corpId}", appid).replace("{corpsecret}", appsecret);
        JSONObject jsonObject = JSONObject.parseObject(httpRequest(requestUrl), JSONObject.class);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}" + jsonObject.getInteger("errcode") + ":" + jsonObject.getString("errmsg"));
            }
        }
        return accessToken;
    }

}
@Slf4j
public final class HttpUtil {
    /**
     * 超时时间
     */
    private static final Integer TIMEOUT = 20000;

    private HttpUtil() {

    }

    /**
     * 发送post请求
     *
     * @param url    url
     * @param header header
     * @param body   body
     * @param param  param
     * @return string
     */
    public static String doPost(String url, Map<String, String> header, String body, Map<String, Object> param) {
        String result = "";
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            // 设置 url
            url = getUrl(url, param);
            URL realUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("POST");
            // 设置 header
            if (header != null) {
                for (String key : header.keySet()) {
                    connection.setRequestProperty(key, header.get(key));
                }
            }
            // 设置请求 body
            connection.setDoOutput(true);
            connection.setDoInput(true);

            //设置连接超时和读取超时时间
            connection.setConnectTimeout(TIMEOUT);
            connection.setReadTimeout(TIMEOUT);
            try {
                out = new PrintWriter(connection.getOutputStream());
                // 保存body
                out.print(body);
                // 发送body
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("connection: " + connection);
            log.info("body: " + out);
            try {
                // 获取响应body
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送get请求
     *
     * @param url    url
     * @param header header
     * @param param  param
     * @return string
     */
    public static String doGet(String url, Map<String, String> header, Map<String, Object> param) {
        String result = "";
        BufferedReader in = null;
        try {
            url = getUrl(url, param);
            // 设置 url
            URL realUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setUseCaches(false);
            connection.setRequestMethod("GET");
            // 设置 header
            if (header != null) {
                for (String key : header.keySet()) {
                    connection.setRequestProperty(key, header.get(key));
                }
            }
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
        return result;
    }

    /**
     * @param url   url
     * @param param 请求参数
     * @return String
     */
    public static String getUrl(String url, Map<String, Object> param) {
        if (null != param && param.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder(url);
            stringBuilder.append("?");
            Set<Map.Entry<String, Object>> entries = param.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                stringBuilder.append(entry.getKey() + "=" + entry.getValue() + "&");
            }
            url = stringBuilder.substring(0, stringBuilder.length() - 1);
        }
        return url;
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值