WenXinUti微信群发接口

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("media_id").getAsString());
                }
            }
        } catch (Exception e) {
            log.error("uploadFodder", e);
        }
        return result;
    }

    /**
     * 获取用户组信息
     * 
     * @param url
     *            访问url
     * @param token
     *            access_token
     * @return id字符串,每个id以,分割
     */
    public static Map getGroups(String token) {
        String groupurl = String.format("%s?access_token=%s", GET_USER_GROUP, token);
        HttpGet get = new HttpGet(groupurl);
        Map result = null;
        try {
            // ---本地环境设置代理地址,代理端口号,协议类型----
            // HttpHost proxy = new HttpHost("proxy2.zte.com.cn", 80, "http");
            // RequestConfig config =
            // RequestConfig.custom().setProxy(proxy).build();
            // get.setConfig(config);
            // ------------------------------------

            HttpResponse res = httpClient.execute(get);
            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();// 将json字符串转换为json对象
                if (json.get("errcode") == null)// 不存在错误消息,成功返回
                {
                    JsonArray groups = json.getAsJsonArray("groups"); // 返回对象数组
                    result = new HashMap();
                    for (int i = 0; i < groups.size(); i++) {
                        result.put(groups.get(i).getAsJsonObject().get("id").getAsString(), groups.get(i)
                                .getAsJsonObject().get("name").getAsString());
                    }
                }
            }
        } catch (Exception e) {
            log.error("getGroups", e);
        }
        return result;
    }

    public static WeiXinVo sendMsg(String access_token, String data) {
        WeiXinVo result = null;
        String posturl = String.format("%s?access_token=%s", SEND_MESSAGE_URL, access_token);
        try {
            String returnStr = SendURLUtil.sendPostReq(posturl, data);
            log.debug(returnStr);
            if (returnStr != null) {
                JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
                JsonObject json = jsonparer.parse(returnStr).getAsJsonObject();
                if (json.get("errcode") != null) {
                    result = new WeiXinVo();
                    result.setErrcode(json.get("errcode").getAsString());
                    result.setErrmsg(json.get("errmsg").getAsString());
                }
            }
        } catch (Exception e) {
            log.error("sendMsg", e);
        }
        return result;
    }

    public static WeiXinVo preview(String access_token, String data) {
        WeiXinVo result = null;
        String posturl = String.format("%s?access_token=%s", PREVIEW_MESSAGE_URL, access_token);
        try {
            String returnStr = SendURLUtil.sendPostReq(posturl, data);
            log.debug(returnStr);
            if (returnStr != null) {
                JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
                JsonObject json = jsonparer.parse(returnStr).getAsJsonObject();
                if (json.get("errcode") != null) {
                    result = new WeiXinVo();
                    result.setErrcode(json.get("errcode").getAsString());
                    result.setErrmsg(json.get("errmsg").getAsString());
                }
            }
        } catch (Exception e) {
            log.error("preview", e);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("=========获取token=========");
        // 获取token
        String accessToken = getToken(APP_ID, SECRET).getAccess_token();
        // String accessToken =
        // "l6ESs-DCOGDNezuInssayoy__5FMos4UqNWrPivWF31Wu_OlfwYWQ7GW3cVc95gJ8xA_EyqiwQLBfDIw1Q-sY3O6Q42T8TeQ3CWVOT7xl4Q";
        if (accessToken != null)// token成功获取
        {
            System.out.println("accessToken=" + accessToken);
            // String id = uploadImage(accessToken, "image", new
            // File("d:/1445222098744.png")).getMedia_id();
            String id = "T60saI0LQx3CtcPLDLq570bvcmoD-urtRfW0fH6teoTDt14c6GweT8Yqn4RISolh";
            System.out.println(id);
            if (id != null) {

                String url = uploadImg(accessToken, new File("d:/1445222098744.png")).getUrl();
                // 构造数据
                Map map = new HashMap();
                map.put("thumb_media_id", id);
                map.put("author", "wxx");
                map.put("content_source_url", "www.baidu.com");
                map.put("title", "标题");
                map.put("content", "测试fdsfdsfsdfssfdsfsdfsdfs");
                map.put("digest", "digest");
                map.put("show_cover_pic", "0");

                Map map2 = new HashMap();
                map2.put("thumb_media_id", id);
                map2.put("author", "wxx2");
                map2.put("content_source_url", "www.google.com");
                map2.put("title", "标题2");
                map2.put("content", "测试fdsfdsfsdfssfdsfsdfsdfs2");
                map2.put("digest", "digest2");
                map.put("show_cover_pic", "1");

                Map map3 = new HashMap();
                List list = new ArrayList();
                list.add(map);
                list.add(map2);
                map3.put("articles", list);

                Gson gson = new GsonBuilder().disableHtmlEscaping().create();
                String result = gson.toJson(map3);// 转换成json数据格式
                String mediaId = uploadFodder(accessToken, result).getMedia_id();
                // String mediaId =
                // "OaxtLWxv2aRLjsIEQDdByZfk23HemYQi7lh-ML8686TnUOBepaP3FFMxMHCofkxy";
                System.out.println(mediaId);

                if (mediaId != null) {
                    // Map ids = getGroups(
                    // accessToken);
                    // System.out.println("分组ids=" + ids);
                    /*
                     * if (ids != null && !ids.isEmpty()) { for (String key :
                     * ids.keySet()) { Map jObj = new HashMap(); Map filter =
                     * new HashMap(); filter.put("group_id", key);
                     * jObj.put("filter", JsonUtil.Object2String(filter));
                     * 
                     * Map mpnews = new HashMap(); mpnews.put("media_id",
                     * mediaId); jObj.put("mpnews",
                     * JsonUtil.Object2String(mpnews));
                     * 
                     * jObj.put("msgtype", "mpnews");
                     * 
                     * String result2 = sendMsg(SEND_MESSAGE_URL, accessToken,
                     * jObj); System.out.println(result2); }
                     */

                    JsonObject jObj1 = new JsonObject();
                    // jObj1.addProperty("touser",
                    // "otiXcs3AFDDhx9v-ql-rZ0XlIRX0");
                    jObj1.addProperty("towxname", "hjxgood");
                    JsonObject mpnews1 = new JsonObject();
                    mpnews1.addProperty("media_id", mediaId);
                    jObj1.add("mpnews", mpnews1);
                    jObj1.addProperty("msgtype", "mpnews");
                    System.out.println(jObj1.toString());
                    WeiXinVo result1 = preview(accessToken, jObj1.toString());
                    System.out.println(result1.getErrcode());

                    // JsonObject jObj = new JsonObject();
                    // JsonObject filter = new JsonObject();
                    // filter.addProperty("is_to_all", true);
                    // // filter.addProperty("group_id", "101");
                    // // filter.addProperty("group_id", "0");
                    // jObj.add("filter", filter);
                    // JsonObject mpnews = new JsonObject();
                    // mpnews.addProperty("media_id", mediaId);
                    // jObj.add("mpnews", mpnews);
                    //
                    // jObj.addProperty("msgtype", "mpnews");
                    // System.out.println(jObj.toString());

                    // ErrorVo result2 = sendMsg(accessToken, jObj.toString());
                    // System.out.println(result2.getErrorCode());

                }

            }

        }
    }
}



public class WeiXinVo {
    private String access_token;


    private String media_id;


    private String errcode;


    private String errmsg;


    private String url;


    public String getAccess_token() {
        return access_token;
    }


    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }


    public String getMedia_id() {
        return media_id;
    }


    public void setMedia_id(String media_id) {
        this.media_id = media_id;
    }


    public String getErrcode() {
        return errcode;
    }


    public void setErrcode(String errcode) {
        this.errcode = errcode;
    }


    public String getErrmsg() {
        return errmsg;
    }


    public void setErrmsg(String errmsg) {
        this.errmsg = errmsg;
    }


    public String getUrl() {
        return url;
    }


    public void setUrl(String url) {
        this.url = url;
    }


}



import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SendURLUtil {

    private static URL sUrl = null;
    private static HttpURLConnection httpURlConnection = null;
    private static final Logger logger = LoggerFactory.getLogger(SendURLUtil.class);

    /*
     * 发送url地址并获取响应消息
     */
    public static String sendURL(String url, String encode) {
        BufferedReader reader = null;
        String result = null;
        // ByteArrayOutputStream baos = null;
        try {
            // 发送请求
            sUrl = new URL(url);

            // SocketAddress addr = new InetSocketAddress("proxy2.xxx.com.cn",
            // 80);
            // Proxy typeProxy = new Proxy(Proxy.Type.HTTP, addr);
            // httpURlConnection = (HttpURLConnection)
            // sUrl.openConnection(typeProxy);

            httpURlConnection = (HttpURLConnection) sUrl.openConnection();
            httpURlConnection.setRequestMethod("POST");
            httpURlConnection.setDoOutput(true);
            httpURlConnection.setDoInput(true);
            // 设置连接主机超时
            httpURlConnection.setConnectTimeout(15000);
            // 设置从主机读取数据超时
            httpURlConnection.setReadTimeout(120000);
            httpURlConnection.setUseCaches(false);

            // 设定传送的内容类型是可序列化的java对象
            httpURlConnection.setRequestProperty("Content-type", "text/xml");

            httpURlConnection.connect();

            // 读取返回内容
            StringBuffer buffer = new StringBuffer();
            reader = new BufferedReader(new InputStreamReader(httpURlConnection.getInputStream(), encode));
            String temp;
            while ((temp = reader.readLine()) != null) {
                buffer.append(temp);
            }
            result = buffer.toString();
            // int i = -1;
            // baos = new ByteArrayOutputStream();
            // while ((i = reader.read()) != -1) {
            // baos.write(i);
            // }
            // result = baos.toString();
        } catch (Exception e) {
            logger.error("请求异常:", e);
            return null;
        } finally {
            try {
                if (httpURlConnection != null) {
                    httpURlConnection.disconnect();
                }
            } catch (Exception e) {
                logger.error("錯誤:", e);
            }
            // 关闭输入输出流
            IOUtils.closeQuietly(reader);
            // IOUtils.closeQuietly(baos);

        }
        return result;
    }

    /*
     * 发送post请求获取响应消息
     */
    public static String sendPostReq(String url, String content) throws Exception {
        String result = null;
        DataOutputStream outStrm = null;
        BufferedReader reader = null;
        ByteArrayOutputStream baos = null;
        try {
            // 发送请求
            sUrl = new URL(url);

            // 本地环境需要设置代理
            SocketAddress addr = new InetSocketAddress("proxy2.xxx.com.cn", 80);
            Proxy typeProxy = new Proxy(Proxy.Type.HTTP, addr);
            httpURlConnection = (HttpURLConnection) sUrl.openConnection(typeProxy);

            // httpURlConnection = (HttpURLConnection) sUrl.openConnection();

            // 设置请求方式,缺省为get方式
            httpURlConnection.setRequestMethod("POST");

            // 设置是否向httpUrlConnection输出,post请求需要设为true,默认情况下是false;
            httpURlConnection.setDoOutput(true);

            // 设置是否从httpUrlConnection读入,默认情况下是true;
            httpURlConnection.setDoInput(true);

            // 设置连接主机超时
            httpURlConnection.setConnectTimeout(15000);

            // 设置从主机读取数据超时
            httpURlConnection.setReadTimeout(120000);
            // Post 请求不能使用缓存
            httpURlConnection.setUseCaches(false);

            // 设定传送的内容类型是可序列化的java对象
            httpURlConnection.setRequestProperty("Content-type", "text/xml");

            // 连接,配置必须要在connect之前完成,
            httpURlConnection.connect();

            // 此处getOutputStream会隐含的进行connect,所以在开发中不调用上述的connect()也可以。
            outStrm = new DataOutputStream(httpURlConnection.getOutputStream());

            // 向对象输出流写出数据,这些数据将存到内存缓冲区中
            outStrm.write(content.toString().getBytes("UTF-8"));

            // 刷新对象输出流,将任何字节都写入潜在的流中(此处为ObjectOutputStream)
            outStrm.flush();

            // 关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中,
            // 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器
            outStrm.close();

            // 读取返回内容

            // inStrm = httpURlConnection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(httpURlConnection.getInputStream(), "utf-8"));
            // <===注意,实际发送请求的代码段就在这里
            // reader = new BufferedReader(new
            // InputStreamReader(httpURlConnection.getInputStream()));
            int i = -1;
            baos = new ByteArrayOutputStream();
            while ((i = reader.read()) != -1) {
                baos.write(i);
            }
            result = baos.toString();

        } catch (Exception e) {
            logger.error("请求异常:" + e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (httpURlConnection != null) {
                    httpURlConnection.disconnect();
                }
            } catch (Exception e) {
                logger.error("錯誤:", e);
            }
            // 关闭输入输出流
            IOUtils.closeQuietly(outStrm);
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(baos);
        }
        return result;
    }

}



/**
 * 图文消息,一个图文消息支持1到10条图文
 *
 * @author Administrator
 *
 */
public class Articles {

    private String thumb_media_id;// 图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得

    private String author;// 图文消息的作者

    private String title;// 图文消息的标题

    private String content_source_url;// 在图文消息页面点击“阅读原文”后的页面

    private String content;// 图文消息页面的内容,支持HTML标签

    private String digest;// 图文消息的描述

    private String show_cover_pic;// 是否显示封面,1为显示,0为不显示

    public String getThumb_media_id() {
        return thumb_media_id;
    }

    public void setThumb_media_id(String thumb_media_id) {
        this.thumb_media_id = thumb_media_id;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent_source_url() {
        return content_source_url;
    }

    public void setContent_source_url(String content_source_url) {
        this.content_source_url = content_source_url;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getDigest() {
        return digest;
    }

    public void setDigest(String digest) {
        this.digest = digest;
    }

    public String getShow_cover_pic() {
        return show_cover_pic;
    }

    public void setShow_cover_pic(String show_cover_pic) {
        this.show_cover_pic = show_cover_pic;
    }

}


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Test {

    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_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 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 String getToken(String apiurl, String appid, String secret) {
        String turl = String.format("%s?grant_type=client_credential&appid=%s&secret=%s", apiurl, appid, secret);
        HttpGet get = new HttpGet(turl);
        JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
        String result = null;
        try {
            // ---本地环境设置代理地址,代理端口号,协议类型----
            HttpHost proxy = new HttpHost("proxy2.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"}
                } else {// 正常情况下{"access_token":"ACCESS_TOKEN","expires_in":7200}
                    result = json.get("access_token").getAsString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

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

        String uploadurl = String.format("%s?access_token=%s&type=%s", 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");
        String result = null;
        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("proxy2.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) {// {"errcode":40004,"errmsg":"invalid media type"}
                                                      // 上传成功{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
                        result = json.get("media_id").getAsString();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    /**
     * 上传素材
     * 
     * @param uploadurl
     *            apiurl
     * @param access_token
     *            访问token
     * @param data
     *            提交数据
     * @return
     */
    public static String uploadFodder(String uploadurl, String access_token, Map params) {

        String posturl = String.format("%s?access_token=%s", uploadurl, access_token);

        HttpPost post = new HttpPost(posturl);
        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");
        String result = null;
        try {
            List pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList(params.size());
                for (Map.Entry entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
            }
            if (pairs != null && pairs.size() > 0) {
                post.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
            }

            // ---本地环境设置代理地址,代理端口号,协议类型----
            HttpHost proxy = new HttpHost("proxy2.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");
                System.out.println(responseContent);
                JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
                JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
                if (json.get("errcode") == null) { // 正确 {
                                                   // "type":"news","media_id":"CsEf3ldqkAYJAU6EJeIkStVDSvffUJ54vqbThMgplD-VJXXof6ctX5fI6-aYyUiQ","created_at":1391857799}
                    result = json.get("media_id").getAsString();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    /**
     * 获取用户组信息
     * 
     * @param url
     *            访问url
     * @param token
     *            access_token
     * @return id字符串,每个id以,分割
     */
    public static String getGroups(String url, String token) {
        String groupurl = String.format("%s?access_token=%s", url, token);
        System.out.println(groupurl);
        HttpGet get = new HttpGet(groupurl);
        String result = null;
        try {
            // ---本地环境设置代理地址,代理端口号,协议类型----
            HttpHost proxy = new HttpHost("proxy2.xxx.com.cn", 80, "http");
            RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
            get.setConfig(config);
            // ------------------------------------

            HttpResponse res = httpClient.execute(get);
            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();// 将json字符串转换为json对象
                if (json.get("errcode") == null)// 不存在错误消息,成功返回
                {
                    JsonArray groups = json.getAsJsonArray("groups"); // 返回对象数组
                    StringBuffer buffer = new StringBuffer();
                    for (int i = 0; i < groups.size(); i++) {
                        buffer.append(groups.get(i).getAsJsonObject().get("id").getAsString() + ",");
                    }
                    result = buffer.toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送消息
     * 
     * @param uploadurl
     *            apiurl
     * @param access_token
     * @param data
     *            发送数据
     * @return
     */
    public static String sendMsg(String url, String token, Map params) {
        String sendurl = String.format("%s?access_token=%s", url, token);
        HttpPost post = new HttpPost(sendurl);
        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");
        String result = null;
        try {
            List pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList(params.size());
                for (Map.Entry entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
            }
            if (pairs != null && pairs.size() > 0) {
                post.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
            }

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

            HttpResponse response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String responseContent = EntityUtils.toString(entity, "UTF-8"); // 响应内容
                System.out.println(responseContent);
                JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
                JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
                if (json.get("errcode") != null && json.get("errcode").getAsString().equals("0")) {
                    result = json.get("errmsg").getAsString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

   
 public static void main(String[] args) throws Exception {
        System.out.println("=========获取token=========");
        // 获取token
        String accessToken = getToken(APP_ID, SECRET).getAccess_token();
        // String accessToken =
        // "l6ESs-DCOGDNezuInssayoy__5FMos4UqNWrPivWF31Wu_OlfwYWQ7GW3cVc95gJ8xA_EyqiwQLBfDIw1Q-sY3O6Q42T8TeQ3CWVOT7xl4Q";
        if (accessToken != null)// token成功获取
        {
            System.out.println("accessToken=" + accessToken);
            // String id = uploadImage(accessToken, "image", new
            // File("d:/1445222098744.png")).getMedia_id();
            String id = "T60saI0LQx3CtcPLDLq570bvcmoD-urtRfW0fH6teoTDt14c6GweT8Yqn4RISolh";
            System.out.println(id);
            if (id != null) {


                String url = uploadImg(accessToken, new File("d:/1445222098744.png")).getUrl();
                // 构造数据
                Map map = new HashMap();
                map.put("thumb_media_id", id);
                map.put("author", "wxx");
                map.put("content_source_url", "www.baidu.com");
                map.put("title", "标题");
                map.put("content", "测试fdsfdsfsdfssfdsfsdfsdfs");
                map.put("digest", "digest");
                map.put("show_cover_pic", "0");


                Map map2 = new HashMap();
                map2.put("thumb_media_id", id);
                map2.put("author", "wxx2");
                map2.put("content_source_url", "www.google.com");
                map2.put("title", "标题2");
                map2.put("content", "测试fdsfdsfsdfssfdsfsdfsdfs2");
                map2.put("digest", "digest2");
                map.put("show_cover_pic", "1");


                Map map3 = new HashMap();
                List list = new ArrayList();
                list.add(map);
                list.add(map2);
                map3.put("articles", list);


                Gson gson = new GsonBuilder().disableHtmlEscaping().create();
                String result = gson.toJson(map3);// 转换成json数据格式
                String mediaId = uploadFodder(accessToken, result).getMedia_id();
                // String mediaId =
                // "OaxtLWxv2aRLjsIEQDdByZfk23HemYQi7lh-ML8686TnUOBepaP3FFMxMHCofkxy";
                System.out.println(mediaId);


                if (mediaId != null) {
                    // Map ids = getGroups(
                    // accessToken);
                    // System.out.println("分组ids=" + ids);
                    /*
                     * if (ids != null && !ids.isEmpty()) { for (String key :
                     * ids.keySet()) { Map jObj = new HashMap(); Map filter =
                     * new HashMap(); filter.put("group_id", key);
                     * jObj.put("filter", JsonUtil.Object2String(filter));
                     * 
                     * Map mpnews = new HashMap(); mpnews.put("media_id",
                     * mediaId); jObj.put("mpnews",
                     * JsonUtil.Object2String(mpnews));
                     * 
                     * jObj.put("msgtype", "mpnews");
                     * 
                     * String result2 = sendMsg(SEND_MESSAGE_URL, accessToken,
                     * jObj); System.out.println(result2); }
                     */


                    JsonObject jObj1 = new JsonObject();
                    // jObj1.addProperty("touser",
                    // "otiXcs3AFDDhx9v-ql-rZ0XlIRX0");
                    jObj1.addProperty("towxname", "hjxgood");
                    JsonObject mpnews1 = new JsonObject();
                    mpnews1.addProperty("media_id", mediaId);
                    jObj1.add("mpnews", mpnews1);
                    jObj1.addProperty("msgtype", "mpnews");
                    System.out.println(jObj1.toString());
                    WeiXinVo result1 = preview(accessToken, jObj1.toString());
                    System.out.println(result1.getErrcode());


                    // JsonObject jObj = new JsonObject();
                    // JsonObject filter = new JsonObject();
                    // filter.addProperty("is_to_all", true);
                    // // filter.addProperty("group_id", "101");
                    // // filter.addProperty("group_id", "0");
                    // jObj.add("filter", filter);
                    // JsonObject mpnews = new JsonObject();
                    // mpnews.addProperty("media_id", mediaId);
                    // jObj.add("mpnews", mpnews);
                    //
                    // jObj.addProperty("msgtype", "mpnews");
                    // System.out.println(jObj.toString());


                    // ErrorVo result2 = sendMsg(accessToken, jObj.toString());
                    // System.out.println(result2.getErrorCode());


                }


            }


        }
    }
}

你可能感兴趣的:(WenXinUti微信群发接口)