WenXinUti微信群发接口

</pre><pre name="code" class="html">public class WeiXinUtil {

    private static final Logger log = LoggerFactory.getLogger(WeiXinUtil.class);

    private static final CloseableHttpClient httpClient;
    public static final String CHARSET = "UTF-8";

    public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";// 获取access
    public static final String UPLOAD_IMAGE_URL = "http://file.api.weixin.qq.com/cgi-bin/media/upload";// 上传多媒体文件
    public static final String UPLOAD_IMG_URL = "https://api.weixin.qq.com/cgi-bin/media/uploadimg";// 上传图文消息内的图片获取URL
    public static final String UPLOAD_FODDER_URL = "https://api.weixin.qq.com/cgi-bin/media/uploadnews";
    public static final String GET_USER_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/get"; // url
    public static final String SEND_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall";
    public static final String PREVIEW_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/preview";

     public static final String APP_ID = "wx2506826adfe1d70e";
     public static final String SECRET = "0fa6d4cb6224d4bde318f8336bb9027f";


    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    // 获取token
    public static WeiXinVo getToken(String appid, String secret) {
        String turl = String.format("%s?grant_type=client_credential&appid=%s&secret=%s", GET_TOKEN_URL, appid, secret);
        HttpGet get = new HttpGet(turl);
        JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
        WeiXinVo result = new WeiXinVo();
        try {
            // ---本地环境设置代理地址,代理端口号,协议类型----
            // HttpHost proxy = new HttpHost("xxx.com.cn", 80, "http");
            // RequestConfig config =
            // RequestConfig.custom().setProxy(proxy).build();
            // get.setConfig(config);
            // ------------------------------------
            HttpResponse res = httpClient.execute(get);
            // 将json字符串转换为json对象
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String responseContent = EntityUtils.toString(entity, "UTF-8");
                JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
                if (json.get("errcode") != null) {// 错误时微信会返回错误码等信息,{"errcode":40013,"errmsg":"invalid appid"}
                    result.setErrcode(json.get("errcode").getAsString());
                    result.setErrmsg(json.get("errmsg").getAsString());
                } else if (json.get("access_token") != null) {// 正常情况下{"access_token":"ACCESS_TOKEN","expires_in":7200}
                    result.setAccess_token(json.get("access_token").getAsString());
                }
            }
        } catch (Exception e) {
            log.error("getToken", e);
        }
        return result;
    }

    /**
     * 上传多媒体文件
     * 
     * @param url
     *            访问url
     * @param access_token
     *            access_token
     * @param type
     *            文件类型
     * @param file
     *            文件对象
     * @return
     * @throws Exception
     */
    @SuppressWarnings("deprecation")
    public static WeiXinVo uploadImage(String access_token, String type, File file) throws Exception {

        String uploadurl = String.format("%s?access_token=%s&type=%s", UPLOAD_IMAGE_URL, access_token, type);
        HttpPost post = new HttpPost(uploadurl);
        post.setHeader("User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0");
        post.setHeader("Host", "file.api.weixin.qq.com");
        post.setHeader("Connection", "Keep-Alive");
        post.setHeader("Cache-Control", "no-cache");
        WeiXinVo result = new WeiXinVo();
        try {
            if (file != null && file.exists()) {

                // 对请求的表单域进行填充
                @SuppressWarnings("deprecation")
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("file", new FileBody(file));
                post.setEntity(reqEntity);

                // ---本地环境设置代理地址,代理端口号,协议类型----
                // HttpHost proxy = new HttpHost("xxx.com.cn", 80,
                // "http");
                // RequestConfig config =
                // RequestConfig.custom().setProxy(proxy).build();
                // post.setConfig(config);
                // ------------------------------------

                HttpResponse res = httpClient.execute(post);
                if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entity = res.getEntity();
                    String responseContent = EntityUtils.toString(entity, "UTF-8");
                    JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
                    JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
                    if (json.get("errcode") != null) {
                        result.setErrcode(json.get("errcode").getAsString());
                        result.setErrmsg(json.get("errmsg").getAsString());
                    } else if (json.get("media_id") != null) {// {"errcode":40004,"errmsg":"invalid media type"}
                        // 上传成功{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
                        result.setMedia_id(json.get("media_id").getAsString());
                    }
                }
            }
        } catch (Exception e) {
            log.error("uploadImage", e);
        }
        return result;

    }

    /**
     * 上传图文消息内的图片获取URL
     * 
     * @param access_token
     * @param type
     * @param file
     * @return
     * @throws Exception
     */
    @SuppressWarnings("deprecation")
    public static WeiXinVo uploadImg(String access_token, File file) throws Exception {

        String uploadurl = String.format("%s?access_token=%s", UPLOAD_IMG_URL, access_token);
        HttpPost post = new HttpPost(uploadurl);
        post.setHeader("User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0");
        post.setHeader("Host", "file.api.weixin.qq.com");
        post.setHeader("Connection", "Keep-Alive");
        post.setHeader("Cache-Control", "no-cache");
        WeiXinVo result = new WeiXinVo();
        try {
            if (file != null && file.exists()) {

                // 对请求的表单域进行填充
                @SuppressWarnings("deprecation")
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("file", new FileBody(file));
                post.setEntity(reqEntity);

                // ---本地环境设置代理地址,代理端口号,协议类型----
                // HttpHost proxy = new HttpHost("xxx.com.cn", 80,
                // "http");
                // RequestConfig config =
                // RequestConfig.custom().setProxy(proxy).build();
                // post.setConfig(config);
                // ------------------------------------

                HttpResponse res = httpClient.execute(post);
                if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entity = res.getEntity();
                    String responseContent = EntityUtils.toString(entity, "UTF-8");
                    JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
                    JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
                    if (json.get("errcode") != null) {
                        result.setErrcode(json.get("errcode").getAsString());
                        result.setErrmsg(json.get("errmsg").getAsString());
                    } else if (json.get("url") != null) {
                        result.setUrl(json.get("url").getAsString());
                    }
                }
            }
        } catch (Exception e) {
            log.error("uploadImage", e);
        }
        return result;

    }

    public static WeiXinVo uploadFodder(String access_token, String data) {
        WeiXinVo result = new WeiXinVo();
        String posturl = String.format("%s?access_token=%s", UPLOAD_FODDER_URL, access_token);
        try {
            String returnStr = SendURLUtil.sendPostReq(posturl, data);
            if (returnStr != null) {
                JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
                JsonObject json = jsonparer.parse(returnStr).getAsJsonObject();
                if (json.get("errcode") != null) {
                    result.setErrcode(json.get("errcode").getAsString());
                    result.setErrmsg(json.get("errmsg").getAsString());
                } else if (json.get("media_id") != null) {
                    result.setMedia_id(json.get("medi
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值