向企业微信用户发送消息的实现

企业微信消息推送官方文档
1.工具类
1.1 HttpClientUtils

public class HttpClientUtils {
private static final String CHARSET_UTF8 = "UTF-8";
private static final String CHARSET_GBK = "GBK";
private static final String SSL_DEFAULT_SCHEME = "https";
private static final int SSL_DEFAULT_PORT = 443;// 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复
private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {// 自定义的恢复策略public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {// 设置恢复策略,在发生异常时候将自动重试3次if (executionCount >= 3) {// Do not retry if over max retry countreturn false;}if (exception instanceof NoHttpResponseException) {// Retry if the server dropped connection on usreturn true;}if (exception instanceof SSLHandshakeException) {// Do not retry on SSL handshake exceptionreturn false;}HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);boolean idempotent = (request instanceof HttpEntityEnclosingRequest);if (!idempotent) {// Retry if the request is considered idempotentreturn true;}return false;}
};
// 使用ResponseHandler接口处理响应,HttpClient使用ResponseHandler会自动管理连接的释放,解决了对连接的释放管理
private static ResponseHandler responseHandler = new ResponseHandler() {// 自定义响应处理public String handleResponse(HttpResponse response)  throws ClientProtocolException, IOException {HttpEntity entity = response.getEntity();if (entity != null) {String charset = EntityUtils.getContentCharSet(entity) == null ? CHARSET_UTF8 : EntityUtils.getContentCharSet(entity);return new String(EntityUtils.toByteArray(entity), charset);} else {return null;}}
};
/*** Get方式提交,URL中包含查询参数, 格式:http://www.g.cn?search=p&name=s.....** @param url* 提交地址* @return 响应消息* @throws NetServiceException */
public static String get(String url) throws NetServiceException {return get(url, null, null);
}
/*** Get方式提交,URL中不包含查询参数, 格式:http://www.g.cn** @param url* 提交地址* @param params* 查询参数集, 键/值对* @return 响应消息* @throws NetServiceException */
public static String get(String url, Map params) throws NetServiceException {return get(url, params, null);
}
/*** Get方式提交,URL中不包含查询参数, 格式:http://www.g.cn** @param url* 提交地址* @param params* 查询参数集, 键/值对* @param charset* 参数提交编码集* @return 响应消息* @throws NetServiceException */
public static String get(String url, Map params, String charset) throws NetServiceException {if (url == null || StringUtil.isEmpty(url)) {return null;}List qparams = getParamsList(params);if (qparams != null && qparams.size() > 0) {charset = (charset == null ? CHARSET_UTF8 : charset);String formatParams = URLEncodedUtils.format(qparams, charset);url = (url.indexOf("?")) < 0 ? (url + "?" + formatParams) : (url.substring(0, url.indexOf("?") + 1) + formatParams);}DefaultHttpClient httpclient = getDefaultHttpClient(charset);HttpGet hg = new HttpGet(url);// 发送请求,得到响应String responseStr = null;try {responseStr = httpclient.execute(hg, responseHandler).toString();} catch (ClientProtocolException e) {throw new NetServiceException("客户端连接协议错误", e);} catch (IOException e) {throw new NetServiceException("IO操作异常", e);} finally {abortConnection(hg, httpclient);}return responseStr;
}
/*** Post方式提交,URL中不包含提交参数, 格式:http://www.g.cn** @param url* 提交地址* @param params* 提交参数集, 键/值对* @return 响应消息* @throws NetServiceException */
public static String post(String url, Map params) throws NetServiceException {return post(url, params, null);
}
/*** Post方式提交,URL中不包含提交参数, 格式:http://www.g.cn** @param url* 提交地址* @param params* 提交参数集, 键/值对* @param charset* 参数提交编码集* @return 响应消息* @throws NetServiceException* modified by hxd according to http://blog.csdn.net/rongyongfeikai2/article/details/41659353*/
public static String post(String url, Map params, String charset) throws NetServiceException {if (url == null || StringUtil.isEmpty(url)) {return null;}// 创建HttpClient实例DefaultHttpClient httpclient = getDefaultHttpClient(charset);UrlEncodedFormEntity formEntity = null;try {if (charset == null || StringUtil.isEmpty(charset)) {formEntity = new UrlEncodedFormEntity(getParamsList(params));} else {formEntity = new UrlEncodedFormEntity(getParamsList(params), charset);}} catch (UnsupportedEncodingException e) {throw new NetServiceException("不支持的编码集", e);}HttpPost hp = new HttpPost(url);hp.setEntity(formEntity);// 发送请求,得到响应HttpResponse httpResponse = null;String responseStr = null;try {httpResponse = httpclient.execute(hp);if (null!=httpResponse &&  HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {HttpEntity entity = httpResponse.getEntity();if(entity != null){responseStr = EntityUtils.toString(entity,charset);}}} catch (ClientProtocolException e) {throw new NetServiceException("客户端连接协议错误", e);} catch (IOException e) {throw new NetServiceException("IO操作异常", e);}finally {abortConnection(hp, httpclient);}return responseStr;
}
/*** Post方式提交,忽略URL中包含的参数,解决SSL双向数字证书认证** @param url* 提交地址* @param params* 提交参数集, 键/值对* @param charset* 参数编码集* @param keystoreUrl* 密钥存储库路径* @param keystorePassword* 密钥存储库访问密码* @param truststoreUrl* 信任存储库绝路径* @param truststorePassword* 信任存储库访问密码, 可为null* @return 响应消息* @throws NetServiceException*/
public static String post(String url, Map params, String charset, final URL keystoreUrl,final String keystorePassword, final URL truststoreUrl, final String truststorePassword) throws NetServiceException {if (url == null || StringUtil.isEmpty(url)) {return null;}DefaultHttpClient httpclient = getDefaultHttpClient(charset);UrlEncodedFormEntity formEntity = null;try {if (charset == null || StringUtil.isEmpty(charset)) {formEntity = new UrlEncodedFormEntity(getParamsList(params));} else {formEntity = new UrlEncodedFormEntity(getParamsList(params), charset);}} catch (UnsupportedEncodingException e) {throw new NetServiceException("不支持的编码集", e);}HttpPost hp = null;String responseStr = null;try {KeyStore keyStore = createKeyStore(keystoreUrl, keystorePassword);KeyStore trustStore = createKeyStore(truststoreUrl, keystorePassword);SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore,    keystorePassword, trustStore);Scheme scheme = new Scheme(SSL_DEFAULT_SCHEME, socketFactory, SSL_DEFAULT_PORT);httpclient.getConnectionManager().getSchemeRegistry().register(scheme);hp = new HttpPost(url);hp.setEntity(formEntity);//responseStr = httpclient.execute(hp, responseHandler);} catch (NoSuchAlgorithmException e) {throw new NetServiceException("指定的加密算法不可用", e);} catch (KeyStoreException e) {throw new NetServiceException("keytore解析异常", e);} catch (CertificateException e) {throw new NetServiceException("信任证书过期或解析异常", e);} catch (FileNotFoundException e) {throw new NetServiceException("keystore文件不存在", e);} catch (IOException e) {throw new NetServiceException("I/O操作失败或中断 ", e);} catch (UnrecoverableKeyException e) {throw new NetServiceException("keystore中的密钥无法恢复异常", e);} catch (KeyManagementException e) {throw new NetServiceException("处理密钥管理的操作异常", e);} finally {abortConnection(hp, httpclient);}return responseStr;
}
/*** 获取DefaultHttpClient实例** @param charset* 参数编码集, 可空* @return DefaultHttpClient 对象*/
private static DefaultHttpClient getDefaultHttpClient(final String charset){DefaultHttpClient httpclient = new DefaultHttpClient();httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);//模拟浏览器,解决一些服务器程序只允许浏览器访问的问题httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");httpclient.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset == null ? CHARSET_UTF8 : charset);httpclient.setHttpRequestRetryHandler(requestRetryHandler);return httpclient;
}/*** 释放HttpClient连接** @param hrb* 请求对象* @param httpclient*            client对象*/
private static void abortConnection(final HttpRequestBase hrb, final HttpClient httpclient){if (hrb != null) {hrb.abort();}if (httpclient != null) {httpclient.getConnectionManager().shutdown();}
}/*** 从给定的路径中加载此 KeyStore** @param url* keystore URL路径* @param password* keystore访问密钥* @return keystore 对象*/
private static KeyStore createKeyStore(final URL url, final String password)throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {if (url == null) {throw new IllegalArgumentException("Keystore url may not be null");}KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());InputStream is = null;try {is = url.openStream();keystore.load(is, password != null ? password.toCharArray() : null);} finally {if (is != null){is.close();is = null;}}return keystore;
}/*** 将传入的键/值对参数转换为NameValuePair参数集** @param paramsMap* 参数集, 键/值对* @return NameValuePair参数集*/
private static List getParamsList(Map paramsMap) {if (paramsMap == null || paramsMap.size() == 0) {return null;}List params = new ArrayList();for ( Object o : paramsMap.entrySet()) {Map.Entry map = (Map.Entry)o;params.add(new BasicNameValuePair((String)map.getKey(), (String)map.getValue()));}return params;
}public static String post(String url, String parameters) {String body = null;HttpPost method = new HttpPost(url);DefaultHttpClient httpclient = getDefaultHttpClient("UTF-8");if (method != null & parameters != null&& !"".equals(parameters.trim())) {try {// 建立一个NameValuePair数组,用于存储欲传送的参数method.addHeader("Content-type","application/json; charset=utf-8");method.setHeader("Accept", "application/json");method.setEntity(new StringEntity(parameters, "UTF-8"));HttpResponse response = httpclient.execute(method);int statusCode = response.getStatusLine().getStatusCode();if (statusCode != HttpStatus.SC_OK) {}body = EntityUtils.toString(response.getEntity());} catch (IOException e) {e.printStackTrace();}}return body;
}
}

1.2 WebChatUtil

public class WebChatUtil {public static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={id}&corpsecret={secrect}";
public static String access_token = null;private static final Logger logger = Logger.getLogger(WebChatUtil.class);
private static String ERROR_CODE_0 = "0";
private static int callCnt = 0;/***获取token方法 已验证*/
private static JSONObject doGetStr(String url) throws ClientProtocolException, IOException {DefaultHttpClient client = new DefaultHttpClient();//获取DefaultHttpClient请求HttpGet httpGet = new HttpGet(url);//HttpGet将使用Get方式发送请求URLJSONObject jsonObject = null;HttpResponse response = client.execute(httpGet);//使用HttpResponse接收client执行httpGet的结果HttpEntity entity = response.getEntity();//从response中获取结果,类型为HttpEntityif (entity != null) {String result = EntityUtils.toString(entity, "UTF-8");//HttpEntity转为字符串类型jsonObject = JSONObject.fromObject(result);//字符串类型转为JSON类型}return jsonObject;
}private static String getAccessToken(String appid, String appsecret) throws IOException {String url = access_token_url.replace("{id}", appid).replace("{secrect}", appsecret);//将URL中的两个参数替换掉JSONObject jsonObject = doGetStr(url);//使用刚刚写的doGet方法接收结果if (jsonObject != null) { //如果返回不为空,将返回结果封装进AccessToken实体类try {String errcode = jsonObject.getString("errcode");if (ERROR_CODE_0.equals(errcode)) {access_token = jsonObject.getString("access_token");//取出access_token} else {logger.error(jsonObject.getString("errmsg"));}} catch (JSONException e) {access_token = null;// 获取token失败}}return access_token;
}public static String getToken() {if (access_token == null) {String appid = "CorpID";//企业微信中的IDString appsecret = "corpsecret";//企业微信中提供的改成自己的try {access_token = getAccessToken(appid, appsecret);} catch (IOException e) {e.printStackTrace();}}return access_token;
}public static JSONObject sendWeChatMessageToUser(String touser, String contents){if(oConvertUtils.isEmpty(touser)){return new JSONObject();}JSONObject jo = sendWeChatMessage(touser, null, null, contents);String errcode = jo.getString("errcode");if (!ERROR_CODE_0.equals(errcode)){logger.error("微信信息发送失败,失败用户:"+touser+",失败原因:"+jo.getString("errmsg")+";发送内容为:"+contents+"。");}callCnt = 0;return jo;
}/**微信企业号推送消息*/
public static JSONObject sendWeChatMessage(String touser, String toparty, String totag, String contents){JSONObject jo = new JSONObject();getToken();String url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={ACCESS_TOKEN}";url = url.replace("{ACCESS_TOKEN}", access_token);String agentid = "agentid"; //修改成自己的JSONObject Jo=new JSONObject();Jo.put("touser",touser);if (StringUtil.isNotEmpty(toparty)) {Jo.put("toparty",toparty);}if (StringUtil.isNotEmpty(totag)) {Jo.put("totag",totag);}Jo.put("msgtype","text");Jo.put("agentid",agentid);JSONObject content =new JSONObject();content.put("content",contents);Jo.put("text",content);try {String returnData = HttpClientUtils.post(url, Jo.toString());jo = JSONObject.fromObject(returnData);String errcode = jo.getString("errcode");if (!ERROR_CODE_0.equals(errcode)) {//token过期时重新获取再次请求if (callCnt < 5) {callCnt++;logger.error("token过期,重新获取, 获取时间"+ DateUtils.getTimestamp());access_token = null;jo = sendWeChatMessage(touser, toparty, totag, contents);}}} catch (Exception e) {logger.error(e.getMessage());}return  jo;
}
}

2.测试方法

public static void main(String[] args) {WebChatUtil.sendWeChatMessageToUser("TaoYong","你好呀,陶永");
}

3.结果

通过企业微信Api向企业微信用户发送消息的实现相关推荐

  1. 用微信API给指定的用户发送消息

    API:https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=23_4ql1vcosifp2Px1ivVWrMXJE1O ...

  2. 微信服务号向特定用户发送消息的解决方案

    查找了微信开发文档和一些博客后发现了解决方案. 使用微信服务号的模板消息接口 文档地址: https://mp.weixin.qq.com/wiki?t=resource/res_main&i ...

  3. 【.net】通过企业微信web api给指定用户发送消息

    前言 在很多业务场景中经常会遇到与微博微信进行通信的需求,今天就和大家一起研究一下如果通过企业微信web api给指定用户发送消息 一.创建应用 1.打开企业微信并登录 https://work.we ...

  4. php微信 发送信息,PHP微信企业号主动给用户发送消息接口代码

    php微信企业号主动给用户发送消息接口代码 $corpid = "wx690e2a9380e2440dyt"; $secrect = "3g9l6dHy8qjYqYMWX ...

  5. 亚马逊 开发者api 调用_关于微信API:常用微信API文档整理

    微信公众平台消息接口为开发者提供了一种新的消息处理方式.微信公众平台消息接口为开发者提供与用户进行消息交互的能力.对于成功接入消息接口的微信公众账号,当用户发消息给公众号,微信公众平台服务器会使用HT ...

  6. php 向公众号发送消息,微信公众号之主动给用户发送消息功能

    前一段时间项目中遇到一个稍微麻烦一点的问题. 即客户要求,他在后台编辑好文章后要主动给每个用户都发送消息,并可以让用户点击直接进入文章页面. 于是乎,当时脑子一热,想着没什么大的问题,so easy. ...

  7. java实现微信小程序客服功能开发,后台接受用户发送消息实现关键词自动回复

    最近做了一个小程序中间用到了小程序客服功能,主要实现采集用户提问,并且针对关键词自动回复及手动回复.中间踩过很多坑,所也现在记录下来提供给大家. 准备 首先准备一个小程序,配置好域名,左边菜单栏目点击 ...

  8. 微信公众号利用客服接口主动给用户发送消息的方法

    目前微信并没有放出主动给用户发送消息的接口,但是我们可以使用其多客服接口来达到主动给用户发送消息的目的. 当用户和公众号产生特定动作的交互时(具体动作列表请见下方说明),微信将会把消息数据推送给开发者 ...

  9. 个人微信api接口调用-微信群管理

    个人微信api接口调用-微信群管理 /*** 微信群聊管理* @author wechatno:tangjinjinwx* @blog http://www.wlkankan.cn*/@Asyncpu ...

  10. 【微信小程序】实战案例 -- 向订阅用户发送消息(范例:报名提醒)

    范例场景描述 活动发起人发起了一场活动,在有人通过微信小程序报名活动时,活动发起人/活动报名审核人员希望可以收到一条报名处理提醒消息. 实现流程 1. 选用订阅模板 登录到小程序后台 找到满足需求的模 ...

最新文章

  1. Python Redis
  2. CentOS6安装MySQL 2 - yum makecache成功
  3. 第47讲:scrapy-redis分布式爬虫介绍
  4. LwIP之网络技术基础
  5. series、dataframe转为tensor格式数据
  6. 连锁加盟网站源码_连锁60秒:招商只是开始,养商才最重要
  7. loadrunner中定义数组
  8. 在线问卷工具LimeSurvey
  9. element table实现前端分页
  10. 运行Android Studio,一直提示:Error running app: Instant Run requires 'Tools | Android | Enable ADB integrat
  11. 小伙获25位美国总统签名 价值数百万(图)
  12. Qt编写可视化大屏电子看板系统18-柱状分组图
  13. A. Frog Jumping
  14. css3绘制常见的30种形状(心形,五角星,六边形,钻石,对话框,阴阳鱼图等)
  15. java中怎么定义true或false_java 中的true、false、null有何不同
  16. 快递取件码生成软件_一种分布式的取件码生成方法技术
  17. 基于STM32F4的四轴航拍飞行器(开源)
  18. InfluxDB SpringBoot Docker Grafana实战监控数据统计
  19. 与成都嘉兰图合作了 开启工业设计众包模式
  20. Struts 一些重要的常见的错误2

热门文章

  1. 关于举办“2019 年全国传智杯 IT 技能大赛”的通知
  2. 互联网IT工程师需要具备哪些技能?
  3. Java依赖包下载地址
  4. 最优化算法之鲍威尔算法(java)
  5. 即时通讯工具的基本功能和如何做防御
  6. 久其报表大厅_久其报表大厅[Web版]操作手册.pdf
  7. 关于数据中心PUE与计算机节能的探讨
  8. (ISC)² 新增两家 CISSP 官方授权培训合作伙伴
  9. 画图软件gliffy
  10. 怎么删除服务中的mysql服务