向微信公众号发送消息

向微信公众号发送文本消息
       首先说下需求,在项目中有时需要时时的知道线上系统的稳定性,防止恶意刷接口,因此就有了线上接口监控系统,时时统计接口在某个时段内调用次数。调用次数超过阀值时进行报警,即向微信公众号发送txt格式消息(接口的详情信息)

1.注册微信公众号(团队的)

  注册地址  https://qy.weixin.qq.com/

  API 开发文档 http://qydev.weixin.qq.com/wiki/index.php

   需要绑定微信号当作管理员(添加应用、管理分组、邀请成员等)

2.实际项目中开发,通过http请求接口

   2.1 创建HttpUtils


import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    public static String get(String url, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //超时设置
        RequestConfig requestConfig = getRequestConfig();
        CloseableHttpResponse response = null;
        try {
            String requestParams = parseParams(params);
            String extraUrl = url + (StringUtils.isEmpty(requestParams) ? "" : "?" + requestParams);
            HttpGet get = new HttpGet(extraUrl);
            get.setConfig(requestConfig);
            response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            LOGGER.error("访问链接异常[GET] url=" + url, e);
            return null;
        } finally {
            if(response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
    }

    public static String post(String url, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = getRequestConfig();
        CloseableHttpResponse response = null;
        try {
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parsePairs(params), "UTF-8");
            post.setEntity(entity);
            response = httpClient.execute(post);
            HttpEntity responseEntity = response.getEntity();
            return EntityUtils.toString(responseEntity);
        } catch (Exception e) {
            LOGGER.error("访问链接异常[POST] url=" + url, e);
            return null;
        } finally {
            if(response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
    }

    public static String post(String url, String text) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = getRequestConfig();
        CloseableHttpResponse response = null;
        try {
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            StringEntity entity = new StringEntity(text, "UTF-8");
            post.setEntity(entity);
            response = httpClient.execute(post);
            HttpEntity responseEntity = response.getEntity();
            return EntityUtils.toString(responseEntity);
        } catch (Exception e) {
            LOGGER.error("访问链接异常[POST] url=" + url, e);
            return null;
        } finally {
            if(response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
    }

    /**
     * 设置HTTP配置
     * 3秒超时
     * @return
     */
    private static RequestConfig getRequestConfig() {
        return RequestConfig.custom()
                .setConnectionRequestTimeout(3000).setConnectTimeout(3000)
                .setSocketTimeout(3000).build();
    }

    @SuppressWarnings("unchecked")
    private static String parseParams(Map<String, Object> params) throws Exception{
        if(CollectionUtils.isEmpty(params)) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            Object value = params.get(key);
            if (value == null) {
                continue;
            }
            if (value.getClass().isArray()) {
                for (int i = 0; i < Array.getLength(value); i++) {
                    String item = URLEncoder.encode(Array.get(value, i).toString(), "UTF-8");
                    sb.append(key).append('=').append(item).append('&');
                }
            } else if(value instanceof List) {
                List<Object> items = (List<Object>) value;
                for (Object item : items) {
                    String str = URLEncoder.encode(item.toString(), "UTF-8");
                    sb.append(key).append('=').append(str).append('&');
                }
            } else {
                String str = URLEncoder.encode(value.toString(), "UTF-8");
                sb.append(key).append('=').append(str).append('&');
            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    @SuppressWarnings("unchecked")
    private static List<BasicNameValuePair> parsePairs(Map<String, Object> params) {
        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
        if(CollectionUtils.isEmpty(params)) {
            return list;
        }

        for (String key : params.keySet()) {
            Object value = params.get(key);
            if (value == null) {
                continue;
            }
            if (value.getClass().isArray()) {
                for (int i = 0; i < Array.getLength(value); i++) {
                    String item = Array.get(value, i).toString();
                    list.add(new BasicNameValuePair(key, item));
                }
            } else if(value instanceof List) {
                List<Object> items = (List<Object>) value;
                for (Object item : items) {
                    String str = item.toString();
                    list.add(new BasicNameValuePair(key, str));
                }
            } else {
                String str = value.toString();
                list.add(new BasicNameValuePair(key, str));
            }

        }
        return list;
    }

}
  2.2 创建接口(项目中使用Spring, 写成一个服务供调用比较方便)
    
      MessageData  是我项目中封装的数据对象
public interface WeChatService {
    WeChatSendMsgResponse sendMessage(MessageData data);
}
   2.3 创建实现类


import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wanghaiyang on 2016/3/22.
 */
@Service
public class WeChatServiceImpl implements WeChatService {

    private static final Logger LOGGER = LoggerFactory.getLogger(WeChatServiceImpl.class);

    private static volatile Long sendTimestamp = null;
    //参数通过Spring注解读取const.properties文件赋值
    @Value("${WeChat_Gettoken_Url}")
    private String getTokenUrl;

    @Value("${WeChat_CropID}")
    private String corpid;

    @Value("${WeCaht_Secret}")
    private String corpsecret;

    @Value("${WeChat_GetAgentList_Url}")
    private String getAgentUrl;

    @Value("${WeChat_SendMsg_url}")
    private String sendMsgUrl;


    /**
     * 向公众号发送消息
     */
//    @Async
    public WeChatSendMsgResponse sendMessage(MessageData data) {

        Long now = System.currentTimeMillis();
        //存在且小于一小时,则不报警
        if(sendTimestamp != null && Math.abs(now - sendTimestamp) < 3600*1000) {
            return null;
        }

        //获取access_token
        String access_token = getAccessToken();

        //获取agentList
        List<WeChatAgent> chatAgentList = getAgentList(access_token);

        LOGGER.info("[WeChatServiceImpl]发送微信消息:" + data.toString());
        //发送消息
        WeChatSendMsgResponse sendMsgResponse = sendMessage(data, chatAgentList, access_token);

        //报警成功,记录时间戳
        if("0".equals(sendMsgResponse.getErrcode())) {
            sendTimestamp = System.currentTimeMillis();
        }

        return sendMsgResponse;
    }

    /**
     * 获取access_token
     *
     * @return
     */
    public String getAccessToken() {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("corpid", corpid);
        params.put("corpsecret", corpsecret);
        String result = HttpUtils.get(getTokenUrl, params);
        Map<String, Object> formatResult = GsonUtils.fromJson(result, new TypeToken<Map<String, Object>>() {
        });
        return formatResult.get("access_token").toString();
    }

    public List<WeChatAgent> getAgentList(String accessToken) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("access_token", accessToken);
        String result = HttpUtils.get(getAgentUrl, params);
        WeChatGetAgentResponse response = GsonUtils.fromJson(result, WeChatGetAgentResponse.class);
        List<WeChatAgent> list = response.getAgentlist();
        return list;
    }

    public WeChatSendMsgResponse sendMessage(MessageData data, List<WeChatAgent> chatAgentList, String accessToken) {

        String url = sendMsgUrl + accessToken;
        //成员ID列表 特殊情况:指定为@all,则向关注该企业应用的全部成员发送
        String touser = "@all";
        //部门ID列表
        String toparty = "1";
        //标签ID列表
        String totag = "";
        //消息类型
        String msgtype = "text";
        //企业应用的id 发送到
        int agentid = chatAgentList.get(0).getAgentid();
        //消息内容
        String text = data.toString();
        //表示是否是保密消息,0表示否,1表示是,默认0
        String safe = "0";

        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, Object> textMap = new HashMap<String, Object>();
        textMap.put("content", data.toString());

        params.put("touser", touser);
        params.put("toparty", toparty);
        params.put("totag", totag);
        params.put("msgtype", msgtype);
        params.put("agentid", agentid);
        params.put("text", textMap);
        params.put("safe", safe);

        String result = HttpUtils.post(url, GsonUtils.toJson(params));
        WeChatSendMsgResponse response = GsonUtils.fromJson(result, WeChatSendMsgResponse.class);

        return response;
    }
}

3.调用发送消息服务

    @Autowired
    WeChatService weChatService;
     




  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值