package com.tdream.app.jmdress.core.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Type; import java.net.ConnectException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONObject; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.struts2.ServletActionContext; import org.jsoup.Connection.Method; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.opensymphony.xwork2.ActionContext; import com.tdream.app.jmdress.core.model.Fans; import com.tdream.app.jmdress.core.model.Group; import com.tdream.app.jmdress.core.model.WeiXinFans; import com.tdream.app.jmdress.core.model.WeiXinToken; import com.tdream.app.jmdress.core.model.WeiXinTokenCode; import com.tdream.app.jmdress.core.service.ICustomMenuManager; import com.tdream.app.jmdress.core.weixin.model.Menu; import com.tdream.app.jmdress.core.weixin.util.MyX509TrustManager; import com.tdream.framework.context.spring.SpringContextHolder; /** * 利用腾讯的公众平台网页登录方式 * * @author Lumg * */ public class WeixinUtil { private static Logger log = LoggerFactory.getLogger(WeixinUtil.class); public static String TOKEN; public static final String LOGIN_URL = "http://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN"; public static final String SEND_MSG = "http://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&lang=zh_CN"; public static final String CREATE_MENU = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="; public static final String GET_MENU = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token="; public static final String DELETE_MENU = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="; public static final String SEND_TEMPLATE = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="; public static final String APP_ID = "wxe2fcb14798fe30e2";// jiaman public static final String APP_SECRET = "40dd39f3b5e1b29c666eb2a4a2377c14";// jiaman // public static final String APP_ID = "wx816df70b6e75a817";// hisun // public static final String APP_SECRET = // "b20a132194902556974f3c5cc39477c9";// hisun public static final String API_GETTOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"; public static final String TEMPLATE_ID_BAODAN = "4QOCb1gsy1vpl-lJdi3Q9U6TZQiQ2BeFlcolb-USX3dmXr9M_7Dd2Q0gc9SJ__iy"; public static final String TEMPLATE_ID_GONGGAO = "OW1LacmPmU-7KxiO-QBbuRF4FeqTq-0dww5kjMdmue3-NUxTubsDk97qJbysnFHh"; public static final String TEMPLATE_ID_YEJI = "q1BESdAeNLqdT3dSb8yiieMhZkuje14EkDvIeYUXkWNIT9JgkdK0y00sr0F6AlEY"; public static final String OPEN_ID_QJ = "oaqT1jmbDw6cWpSdCUd8Z60NgUU0";// QINJI public static final String OPEN_ID_CZ = "oaqT1jr6KjrJoPclasP0IR2mqzW4";// CZ public static final String OPEN_ID_ZS = "oaqT1jmpFT57AvbjPqzzW4R7cZDE";// ZS public static String API_FANSINFO = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={{accessToken}}&openid={{openId}}"; public static final String loginUser = "chen.zhang@jmdress.com"; public static final String loginPwd = "jmdress888"; // public static final String loginUser = "zhangyq@hisun-tomorrow.com"; // public static final String loginPwd = "460233487"; private HttpClient client = null; private static Cookie[] cookies; private String cookiestr; private String token; private int loginErrCode; private String loginErrMsg; private int msgSendCode; private String msgSendMsg; public boolean isLogin = false; public WeixinUtil() { client = new DefaultHttpClient(); } /** * 获取登录session */ public static void auth(String username, String password) throws IOException { String url = "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN" + "&pwd=" + MD5.getMD5(loginPwd.getBytes()).toUpperCase() + "&username=" + username; org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); PostMethod getMethod = new PostMethod(url); getMethod.setRequestHeader("Referer", "https://mp.weixin.qq.com/"); getMethod.setRequestHeader("Host", "mp.weixin.qq.com"); client.executeMethod(getMethod); cookies = client.getState().getCookies(); String returnStr = getMethod.getResponseBodyAsString(); TOKEN = returnStr.split("token=")[1].split("\"")[0]; // for (int i = 0; i < cookies.length; i++) { // if (cookies[i].getName().equals("slave_user")) { // slave_user = cookies[i].getValue(); // } else if (cookies[i].getName().equals("slave_sid")) { // slave_sid = cookies[i].getValue(); // } // } } /** * 开发者获取使用凭证,可以使用该凭证对公众账号的自定义菜单进行创建、查询和删除等操作 */ public static String getAccessToken() throws IOException { System.out.println("++++getAccessToken ++++"); StringBuffer sb = new StringBuffer(); sb.append(API_GETTOKEN + "&appid=" + APP_ID + "&secret=" + APP_SECRET); Map<String, String> map = new HashMap<String, String>(); map.put("f", "json"); Response response = Jsoup.connect(sb.toString()) .ignoreContentType(true).method(Method.GET).data(map).execute(); // 新添加代码 String json = response.body(); System.out.println(json); Gson gson = new Gson(); WeiXinToken weiXinResponse = gson.fromJson(json, WeiXinToken.class); TOKEN = weiXinResponse.getAccess_token(); System.out.println("++++getAccessToken++++ " + TOKEN); return TOKEN; } /** * 开发者获取使用凭证,可以使用该凭证对公众账号的自定义菜单进行创建、查询和删除等操作 */ public static WeiXinTokenCode getAccessToken(String code) throws IOException { System.out.println("++++getAccessToken ++++"); StringBuffer sb = new StringBuffer(); sb.append("https://api.weixin.qq.com/sns/oauth2/access_token?&appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code + "&grant_type=authorization_code"); Map<String, String> map = new HashMap<String, String>(); map.put("f", "json"); Response response = Jsoup.connect(sb.toString()) .ignoreContentType(true).method(Method.GET).data(map).execute(); // 新添加代码 String json = response.body(); System.out.println(json); Gson gson = new Gson(); WeiXinTokenCode weiXinTokenCode = gson.fromJson(json, WeiXinTokenCode.class); return weiXinTokenCode; } /** * 获取基本的粉丝列表 * * @param cookie * @return * @throws IOException */ public static List<WeiXinFans> getFans(Map<String, String> cookie) throws IOException { // 星标组groupid = 2 ; 黑名单groupid=1 // https://mp.weixin.qq.com/cgi-bin/contactmanagepage?t=wxm-friend&token=1899231582&lang=zh_CN&pagesize=10&pageidx=0&type=0&groupid=0 String FANS_URL = "http://mp.weixin.qq.com/cgi-bin/contactmanagepage?t=wxm-friend&token=" + TOKEN + "&lang=zh_CN&pagesize=10&pageidx=0&type=0&groupid=0"; Document document = Jsoup.connect(FANS_URL).post(); Elements eles = document.select("#json-friendList"); Element element = eles.get(0); String json = element.data(); System.out.println("json===" + json); Gson gson = new Gson(); List<WeiXinFans> fans = gson.fromJson(json, new TypeToken<List<WeiXinFans>>() { }.getType()); return fans; } public static List<String> getFans(String token) throws IOException { List<String> fans = new ArrayList<String>(); // 星标组groupid = 2 ; 黑名单groupid=1 // https://mp.weixin.qq.com/cgi-bin/contactmanagepage?t=wxm-friend&token=1899231582&lang=zh_CN&pagesize=10&pageidx=0&type=0&groupid=0 // String FANS_URL = // "http://mp.weixin.qq.com/cgi-bin/contactmanagepage?t=wxm-friend&token="+TOKEN+"&lang=zh_CN&pagesize=10&pageidx=0&type=0&groupid=0"; String FANS_URL = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + token + "&groupid=1&next_openid="; Document document = Jsoup.connect(FANS_URL).ignoreContentType(true) .get(); Elements eles = document.select("body"); Element element = eles.first(); String json = element.text().trim().replace(" ", ""); System.out.println("json===" + json); Gson gson = new Gson(); Type type = new TypeToken<Map<String, Object>>() { }.getType(); Map<Object, Object> map2 = gson.fromJson(json, type); if ((Double) map2.get("total") == 0.0) { System.out.println("木有粉丝"); } else { fans = (List<String>) ((Map) map2.get("data")).get("openid"); } return fans; } /** * @Title: getFansInfo * @Description: 拉取粉丝的详细信息。。 * @param @param cookie * @param @return * @return Object * @throws */ public static Object getFansInfo(Map<String, String> cookie) throws IOException { API_FANSINFO = API_FANSINFO.replace("{{accessToken}}", TOKEN).replace( "{{openId}}", "oAl3ejhUG5fysbqK296wkdZeDKgg"); Document document = Jsoup.connect(API_FANSINFO).post(); System.out.println("body.data: " + document.body().outerHtml()); return null; } /** * @param token * @return * @throws IOException */ public static Fans getFansInfo(String token, String openId) throws Exception { // token = WeixinUtil.getAccessToken(); // API_FANSINFO = API_FANSINFO.replace("{{accessToken}}", // token).replace("{{openId}}", openId); String api_fansinfo = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + openId; Document document = Jsoup.connect(api_fansinfo).ignoreContentType(true) .get(); // System.out.println("body.data: " + document.body().outerHtml()); Elements eles = document.select("body"); Element element = eles.first(); String json = element.text().trim().replace(" ", ""); System.out.println("json===" + json); Gson gson = new Gson(); Type type = new TypeToken<Map<String, Object>>() { }.getType(); Map<Object, Object> map2 = gson.fromJson(json, type); Fans fans = new Fans(); double subscribe = (Double) map2.get("subscribe"); fans.setSubscribe((int) subscribe); fans.setOpenId((String) map2.get("openid")); String nickname = (String) map2.get("nickname"); // fans.setNickName(new String(nickname.getBytes(), "UTF-8")); // nickname = TranCharset.XmlFormalize(nickname); nickname = BASE64.encryptBASE64(nickname.getBytes()); fans.setNickName(nickname); double sex = (Double) map2.get("sex"); fans.setSex((int) sex); fans.setLanguage((String) map2.get("language")); fans.setCity((String) map2.get("city")); fans.setProvince((String) map2.get("province")); fans.setCountry((String) map2.get("country")); String headimgurl = (String) map2.get("headimgurl"); fans.setHeadimgurl(headimgurl); double subscribe_time = (Double) map2.get("subscribe_time"); fans.setSubscribe_time((long) subscribe_time); if (!headimgurl.equals("")) { downloadImg((String) map2.get("headimgurl"), openId); }else{ copyImg(openId); } return fans; } public static Fans getFansInfo1(String token, String openId,HttpServletRequest request)throws Exception { // API_FANSINFO = API_FANSINFO.replace("{{accessToken}}", // token).replace("{{openId}}", openId); String api_fansinfo = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + openId; Document document = Jsoup.connect(api_fansinfo).ignoreContentType(true) .get(); // System.out.println("body.data: " + document.body().outerHtml()); Elements eles = document.select("body"); Element element = eles.first(); String json = element.text().trim().replace(" ", ""); System.out.println("json===" + json); Gson gson = new Gson(); Type type = new TypeToken<Map<String, Object>>() { }.getType(); Map<Object, Object> map2 = gson.fromJson(json, type); Fans fans = new Fans(); double subscribe = (Double) map2.get("subscribe"); fans.setSubscribe((int) subscribe); fans.setOpenId((String) map2.get("openid")); String nickname = (String) map2.get("nickname"); // fans.setNickName(new String(nickname.getBytes(), "UTF-8")); // nickname = TranCharset.XmlFormalize(nickname); nickname = BASE64.encryptBASE64(nickname.getBytes()); fans.setNickName(nickname); double sex = (Double) map2.get("sex"); fans.setSex((int) sex); fans.setLanguage((String) map2.get("language")); fans.setCity((String) map2.get("city")); fans.setProvince((String) map2.get("province")); fans.setCountry((String) map2.get("country")); String headimgurl = (String) map2.get("headimgurl"); fans.setHeadimgurl(headimgurl); double subscribe_time = (Double) map2.get("subscribe_time"); fans.setSubscribe_time((long) subscribe_time); if (!headimgurl.equals("")) { downloadImg1((String) map2.get("headimgurl"), openId,request); }else{ copyImg1(openId, request); } return fans; } /** * 查询所有分组 * * @param token * @return * @throws IOException */ public static List<Group> getGroup(String token) throws IOException { List<Group> list = new ArrayList<Group>(); if(Util.isNotNull(token)){ String FANS_URL = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=" + token; Document document = Jsoup.connect(FANS_URL).ignoreContentType(true) .post(); Elements eles = document.select("body"); Element element = eles.first(); String json = element.text().trim().replace(" ", ""); System.out.println("json===" + json); Gson gson = new Gson(); Type type = new TypeToken<Map<String, Object>>() { }.getType(); Map<Object, Object> map2 = gson.fromJson(json, type); List<Map> lists = (List<Map>) map2.get("groups"); for (int i = 0; i < lists.size(); i++) { Map map = lists.get(i); Group g = new Group(); double id = (Double) map.get("id"); g.setGroupId((int) id); g.setName((String) map.get("name")); list.add(g); } } return list; } /** * 新建分组 * * @param token * @return * @throws IOException */ public static void createGroup(String token, String name) throws IOException { String url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=" + token; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); // 设置菜单参数 String canshu = "{\"group\":{\"name\":\"" + name + "\"}}"; StringEntity reqEntity = new StringEntity(canshu, "utf-8"); // 设置请求的数据 httppost.setEntity(reqEntity); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println(responseBody); } /** * 修改分组名称 * * @param token * @return * @throws IOException */ public static void updateGroup(String token, String groupid, String name) throws IOException { String url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=" + token; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); // 设置菜单参数 String canshu = "{\"group\":{\"id\":\"" + groupid + "\",\"name\":\"" + name + "\"}}";// {"group":{"id":108,"name":"test2_modify2"}} StringEntity reqEntity = new StringEntity(canshu, "utf-8"); // 设置请求的数据 httppost.setEntity(reqEntity); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println(responseBody); } /** * 移动用户分组 * * @param token * @return * @throws IOException */ public static void moveGroupMember(String token, String openid, String groupid) throws IOException { String url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=" + token; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); // 设置菜单参数 String canshu = "{\"openid\":\"" + openid + "\",\"to_groupid\":\"" + groupid + "\"}";// {"openid":"oDF3iYx0ro3_7jD4HFRDfrjdCM58","to_groupid":108} StringEntity reqEntity = new StringEntity(canshu, "utf-8"); // 设置请求的数据 httppost.setEntity(reqEntity); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println(responseBody); } /** * 发送文本信息 24小时内互动过的 * * @param token * @param openid * @param groupid * @throws IOException */ public static boolean sendText(String token, String openid, String text) throws IOException { String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String canshu = "{\"touser\":\"" + openid + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + text + "\"}}"; StringEntity reqEntity = new StringEntity(canshu, "utf-8"); // 设置请求的数据 httppost.setEntity(reqEntity); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println(responseBody); Gson gson = new Gson(); Map m = gson.fromJson(responseBody, Map.class); String errCode = (String) m.get("errmsg"); if(errCode.equals("ok")){ return true; }else{ return false; } } /** * 发送图片 * * @param token * @param openid * @param text * @throws IOException */ public static boolean sendImage(String token, String openid, String media_id) throws IOException { String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String canshu = "{\"touser\":\"" + openid + "\",\"msgtype\":\"image\",\"image\":{\"media_id\":\"" + media_id + "\"}}"; StringEntity reqEntity = new StringEntity(canshu, "utf-8"); // 设置请求的数据 httppost.setEntity(reqEntity); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println(responseBody); Gson gson = new Gson(); Map m = gson.fromJson(responseBody, Map.class); String errCode = (String) m.get("errmsg"); if(errCode.equals("ok")){ return true; }else{ return false; } } /** * 发送语音 * * @param token * @param openid * @param text * @throws IOException */ public static boolean sendVoice(String token, String openid, String media_id) throws IOException { String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String canshu = "{\"touser\":\"" + openid + "\",\"msgtype\":\"voice\",\"voice\":{\"media_id\":\"" + media_id + "\"}}"; StringEntity reqEntity = new StringEntity(canshu, "utf-8"); // 设置请求的数据 httppost.setEntity(reqEntity); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println(responseBody); Gson gson = new Gson(); Map m = gson.fromJson(responseBody, Map.class); String errCode = (String) m.get("errmsg"); if(errCode.equals("ok")){ return true; }else{ return false; } } /** * 发送视频 * * @param token * @param openid * @param text * @throws IOException */ public static boolean sendVideo(String token, String openid, String media_id, String title, String description) throws IOException { String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String canshu = "{\"touser\":\"" + openid + "\",\"msgtype\":\"video\",\"video\":{\"media_id\":\"" + media_id + "\"\"title\":\"" + title + "\"\"description\":\"" + description + "\"}}"; StringEntity reqEntity = new StringEntity(canshu, "utf-8"); // 设置请求的数据 httppost.setEntity(reqEntity); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println(responseBody); Gson gson = new Gson(); Map m = gson.fromJson(responseBody, Map.class); String errCode = (String) m.get("errmsg"); if(errCode.equals("ok")){ return true; }else{ return false; } } /** * 发送图文消息 * * @param token * @param openid * @param text * @throws IOException */ public static boolean sendNews(String token, String json) throws IOException { String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); StringEntity reqEntity = new StringEntity(json, "utf-8"); // 设置请求的数据 httppost.setEntity(reqEntity); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println(responseBody); Gson gson = new Gson(); Map m = gson.fromJson(responseBody, Map.class); String errCode = (String) m.get("errmsg"); if(errCode.equals("ok")){ return true; }else{ return false; } } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~自定义菜单start~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * 发起https请求并获取结果 * * @param requestUrl * 请求地址 * @param requestMethod * 请求方式(GET、POST) * @param outputStr * 提交的数据 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) */ public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // 创建SSLContext对象,并使用我们指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url .openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 当有数据需要提交时 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意编码格式,防止中文乱码 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 将返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader( inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader( inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { log.error("Weixin server connection timed out."); } catch (Exception e) { log.error("https request error:{}", e); } return jsonObject; } /** * 通过POST一个特定结构体,实现在微信客户端创建自定义菜单 * 创建自定义菜单后,由于微信客户端缓存,需要24小时微信客户端才会展现出来。建议测试时可以尝试取消关注公众账号后,再次关注,则可以看到创建后的效果。 * 用户点击click类型按钮后 ,微信服务器会通过消息接口(event类型)推送点击事件给开发者,并且带上按钮中开发者填写的key值, * 开发者可以通过自定义的key值进行消息回复。 * * @return 0表示成功,其他值表示失败 */ public static int createMenu() throws IOException { System.out.println("++++CREATE MENU START ++++"); String token = getAccessToken(); String url = CREATE_MENU + token; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); ICustomMenuManager customMenuManager = SpringContextHolder .getBean("customMenuManager"); Menu menu = customMenuManager.queryForMenu(); // 将菜单对象转换成json字符串 String jsonMenu = JSONObject.fromObject(menu).toString(); System.out.println(jsonMenu); // 设置菜单参数 StringEntity reqEntity = new StringEntity(jsonMenu, "utf-8"); // // 设置请求的数据 httppost.setEntity(reqEntity); String responseBody = httpclient.execute(httppost, responseHandler); JSONObject jsonObject = JSONObject.fromObject(responseBody); int result = 0; if (null != jsonObject) { if (0 != jsonObject.getInt("errcode")) { result = jsonObject.getInt("errcode"); log.error("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } System.out.println(menu); System.out.println(responseBody); System.out.println("++++CREATE MENU END+++"); return result; } /** * 查询当前使用的自定义菜单结构 */ public static String getMenu() throws IOException { System.out.println("++++获取自定义菜单start ++++"); String token = getAccessToken(); String url = GET_MENU + token; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpGet httpget = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); // 设置菜单参数 String responseBody = httpclient.execute(httpget, responseHandler); responseBody = new String(responseBody.getBytes("iso-8859-1"), "UTF-8"); System.out.println(responseBody); System.out.println("++++获取自定义菜单end +++"); return responseBody; } /** * 取消当前使用的自定义菜单 */ private static String deleteMenu() throws IOException { System.out.println("++++DELETE MENU START ++++"); String token = getAccessToken(); String url = DELETE_MENU + token; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpGet httpget = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); // 设置菜单参数 String responseBody = httpclient.execute(httpget, responseHandler); System.out.println(responseBody); System.out.println("++++DELETE MENU END+++"); return responseBody; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~自定义菜单end~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * 自定义模板消息推送 * * @param templateId * 模板ID * @param templateContent * 模板标签和值 * @param openId * 模板标签和值 * @param accessToken * 访问token * @throws IOException */ public static void sendTemplate(String templateId, Map<String, String> templateContent, String openId, String accessToken) throws IOException { System.out.println("++++sendTemplate START ++++"); String url = SEND_TEMPLATE + accessToken; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); StringBuffer sb = new StringBuffer(); sb.append("{\"touser\": \"" + openId + "\",\"template_id\": \"" + templateId + "\",\"data\":"); Gson gs = new Gson(); if (templateId.equals(TEMPLATE_ID_YEJI)) { sb.append(gs.toJson(templateContent)); } sb.append("}"); // 设置菜单参数 StringEntity reqEntity = new StringEntity(sb.toString(), "utf-8"); // 设置请求的数据 httppost.setEntity(reqEntity); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println(sb.toString()); System.out.println(responseBody); System.out.println("++++sendTemplate END+++"); } /** * 发送消息 */ public static void sendNews(Map<String, String> cookie, String content, String fakeId) throws IOException { HashMap<String, String> map = new HashMap<String, String>(); map.put("tofakeid", fakeId); map.put("content", content); map.put("error", "false"); map.put("token", TOKEN); map.put("type", "1"); map.put("ajax", "1"); String referrerUrl = "http://mp.weixin.qq.com/cgi-bin/singlemsgpage?token=" + TOKEN + "&fromfakeid=" + fakeId + "&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN"; Document document = Jsoup.connect(SEND_MSG).referrer(referrerUrl) .data(map).cookies(cookie).post(); Element body = document.body(); System.out.println(body.text()); } /** * 下载图片 * * @param headurl * @param openid * @throws Exception */ public static void downloadImg(String headurl, String openid) throws Exception { ActionContext ctx = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) ctx .get(ServletActionContext.HTTP_REQUEST); String basePaths = request.getSession().getServletContext() .getRealPath("/"); String basePath = basePaths.replace("\\", "/"); URL url = new URL(headurl);// 图片地址 File outFile = new File(basePath + "download/" + openid + ".jpg"); // “图片保存到本地路径 OutputStream os = new FileOutputStream(outFile); InputStream is = url.openStream(); byte[] buff = new byte[1024]; while (true) { int readed = is.read(buff); if (readed == -1) { break; } byte[] temp = new byte[readed]; System.arraycopy(buff, 0, temp, 0, readed); os.write(temp); } is.close(); os.close(); } public static void downloadImg1(String headurl, String openid,HttpServletRequest request) throws Exception { String basePaths = request.getSession().getServletContext() .getRealPath("/"); String basePath = basePaths.replace("\\", "/"); URL url = new URL(headurl);// 图片地址 File outFile = new File(basePath + "download/" + openid + ".jpg"); // “图片保存到本地路径 OutputStream os = new FileOutputStream(outFile); InputStream is = url.openStream(); byte[] buff = new byte[1024]; while (true) { int readed = is.read(buff); if (readed == -1) { break; } byte[] temp = new byte[readed]; System.arraycopy(buff, 0, temp, 0, readed); os.write(temp); } is.close(); os.close(); } public static void copyImg(String openid) throws Exception{ ActionContext ctx = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) ctx .get(ServletActionContext.HTTP_REQUEST); String basePaths = request.getSession().getServletContext() .getRealPath("/"); String basePath = basePaths.replace("\\", "/"); FileInputStream fi=new FileInputStream(basePath + "download/default.jpg"); BufferedInputStream in=new BufferedInputStream(fi); FileOutputStream fo=new FileOutputStream(basePath + "download/" + openid + ".jpg"); BufferedOutputStream out=new BufferedOutputStream(fo); byte[] buf=new byte[1024]; int len=in.read(buf);//读文件,将读到的内容放入到buf数组中,返回的是读到的长度 while(len!=-1){ out.write(buf, 0, len); len=in.read(buf); } out.close(); fo.close(); in.close(); fi.close(); } public static void copyImg1(String openid,HttpServletRequest request ) throws Exception{ String basePaths = request.getSession().getServletContext() .getRealPath("/"); String basePath = basePaths.replace("\\", "/"); FileInputStream fi=new FileInputStream(basePath + "download/default.jpg"); BufferedInputStream in=new BufferedInputStream(fi); FileOutputStream fo=new FileOutputStream(basePath + "download/" + openid + ".jpg"); BufferedOutputStream out=new BufferedOutputStream(fo); byte[] buf=new byte[1024]; int len=in.read(buf);//读文件,将读到的内容放入到buf数组中,返回的是读到的长度 while(len!=-1){ out.write(buf, 0, len); len=in.read(buf); } out.close(); fo.close(); in.close(); fi.close(); } public static void main(String[] args) throws IOException { String token = getAccessToken(); // WeixinUtil mic = new WeixinUtil(); // mic.login(); // deleteMenu(); // getMenu(); // String menus = // "{\"button\":[{\"name\":\"优享汇\",\"sub_button\":[{\"type\":\"view\",\"name\":\"优享汇介绍\",\"url\":\"http://112.64.185.153/mic/s_club_instro.jsp\"},{\"type\":\"view\",\"name\":\"优享汇章程\",\"url\":\"http://112.64.185.153/mic/s_club_rules.jsp\"},{\"type\":\"view\",\"name\":\"常见问题解答\",\"url\":\"http://112.64.185.153/mic/s_club_faq.jsp\"}]},{\"name\":\"明星表彰\",\"sub_button\":[{\"type\":\"click\",\"name\":\"卓越旅程\",\"key\":\"vc_star_travel\"},{\"type\":\"click\",\"name\":\"荣誉殿堂\",\"key\":\"vc_star_honour\"},{\"type\":\"click\",\"name\":\"心筑承诺\",\"key\":\"vc_star_promise\"}]},{\"name\":\"客户服务\",\"sub_button\":[{\"type\":\"click\",\"name\":\"服务承诺\",\"key\":\"vc_service_promise\"},{\"type\":\"click\",\"name\":\"道路救援\",\"key\":\"vc_service_help\"},{\"type\":\"click\",\"name\":\"客户绑定\",\"key\":\"vc_service_bind\"},{\"type\":\"click\",\"name\":\"客户建议\",\"key\":\"vc_service_advice\"}]}]}"; // menus = // "{\"button\":[{\"name\":\"保单查询\",\"sub_button\":[{\"type\":\"click\",\"name\":\"分红信息查询\",\"key\":\"cl_bonus_query\"},{\"type\":\"click\",\"name\":\"交费查询\",\"key\":\"cl_pay_query\"}]},{\"name\":\"关于国寿\",\"sub_button\":[{\"type\":\"click\",\"name\":\"公司品牌\",\"key\":\"cl_company_instr\"},{\"type\":\"click\",\"name\":\"产品特色\",\"key\":\"cl_company_product\"}]},{\"name\":\"贴心助手\",\"sub_button\":[{\"type\":\"click\",\"name\":\"投保规则\",\"key\":\"cl_rules_1\"},{\"type\":\"click\",\"name\":\"保全规则\",\"key\":\"cl_rules_2\"},{\"type\":\"click\",\"name\":\"贵宾热线\",\"key\":\"cl_vip_hotline\"}]}]}"; // MicUtil.createMenu(menus); boolean s = sendText(token, "oc4mIjr7BFnfICpNxBH6aiqRNKHQ", "小样这是测试!!"); System.out.println(s); //sendNews(token, "oc4mIjr7BFnfICpNxBH6aiqRNKHQ"); // getMenu(); //sendNews(token, "oc4mIji-_diwYy4Mkbcr7AIZNgAo"); // sendVoice(token, "oc4mIjurlo_BHpTaRL-jcxP72Jpk", // "XWg84LhLEyfxlED0rqj8B2yIi4S3EWvnwxoHPwogjjEBBIvG70-B-jmojbFQdkEh"); // sendVideo(token, "oc4mIjurlo_BHpTaRL-jcxP72Jpk", // "iUYJpyT_1ynu9JY-Q91ND6a_L9xvmy3V2XgozeU57fnrNZcg4e3jdw-CL0Gq_EJr","标题","很好的描述"); // getGroup(token); // createGroup(token,"234234"); // updateGroup(token,"100","2哈哈哈asd"); // moveGroupMember(token,"oc4mIjhLgJvviRRMz4xl7yQOVbWU","100"); // auth(loginUser, loginPwd); // //获取粉丝列表 // List<String> list = // getFans("uObW6NexUa2KZBlD2jbbw4sfDXKR8oW0RSYjdj2biLFcuBZfRs2CCDDa9df_yIjxbZ1JX9IOiHKohVFhNkVWN_KYLFeuwwHS6T4HKewykiFsicCEJIzX0IlDYrJQy7_vpAdqxVw5fR8Znm8NGXGGUQ"); // for(String f:list){ // System.out.println(f); // } // getFansInfo("r9IM7qFARYaY7gYOPQLHun5adtBMUeu5HlP54F-SqSPbhmPugEt6RDe5P4aRwxxrWGByc_my8bSLGSO1wfC1On7ptUepNBeXgGBMOaiVP7_Dcwu1livZKCR4a7EF5XdidFARHZQb29QkdMbps9Vbww","ohkHUt8oYodlfBCXn5JQjglGUDtA"); // 群发 // for (WeiXinFans fans : list) { // System.out.println(fans); // sendMsg(cookie, "起床了没有", fans.getFakeId()); // } // sendMsg(cookie, "我说能实现主动点对点推送吧 小鬼", "2577274142"); // token = getAccessToken(); /* * String responeJsonStr = "{\"button\":[" + * "{\"name\":\"我的保单\",\"sub_button\":[{\"type\":\"click\",\"name\":\"保单查询\",\"key\":\"V1001_BAODAN_CHAXUN\"},{\"type\":\"click\",\"name\":\"分红查询\",\"key\":\"V1002_FENHONG_CHAXUN\"},{\"type\":\"click\",\"name\":\"交费查询\",\"key\":\"V1003_JIAOFEI_CHAXUN\"}]}," * + * "{\"name\":\"关于新华\",\"sub_button\":[{\"type\":\"click\",\"name\":\"公司品牌\",\"key\":\"V2001_GONGSI_PINPAI\"},{\"type\":\"click\",\"name\":\"公司新闻\",\"key\":\"V2002_GONGSI_XINWEN\"},{\"type\":\"click\",\"name\":\"产品中心\",\"key\":\"V2003_CHANPIN_ZHONGXIN\"}]}," * + * "{\"name\":\"贴心助手\",\"sub_button\":[{\"type\":\"click\",\"name\":\"调查服务\",\"key\":\"V3001_DIAOCHA_FUWU\"},{\"type\":\"click\",\"name\":\"快易理赔\",\"key\":\"V3002_KUAIYI_LIPEI\"},{\"type\":\"click\",\"name\":\"保全规则\",\"key\":\"V3003_BAOQUAN_GUIZE\"},{\"type\":\"click\",\"name\":\"精彩服务\",\"key\":\"V3004_JINGCAI_FUWU\"}]}" * + "]}"; deleteMenu(); createMenu(responeJsonStr); getMenu(); */ // Map<String, String> map = new HashMap<String, String>(); // map.put("Title", "新华业绩战报"); // map.put("Summary", "太好了"); // map.put("Type", "喜报"); // map.put("Date", "2013/7/28"); // map.put("Branch", "北京"); // map.put("FeeTotal", "100万"); // map.put("PlanRate", "80%"); // map.put("ActionRate", "100%"); // map.put("MeritMan1", "绩优人员1"); // map.put("MeritMan2", "绩优人员2"); // map.put("MeritMan3", "绩优人员3"); // map.put("Excitation1", "激励话术1"); // map.put("Excitation2", "激励话术2"); // map.put("Excitation3", "激励话术3"); // map.put("Excitation5", "激励话术4"); // sendTemplate(TEMPLATE_ID_YEJI,map,OPEN_ID_ZS,token); } }
相关推荐
赠送jar包:weixin-java-cp-2.8.0.jar; 赠送原API文档:weixin-java-cp-2.8.0-javadoc.jar; 赠送源代码:weixin-java-cp-2.8.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-cp-2.8.0.pom; 包含翻译后的API...
赠送jar包:weixin-java-mp-3.5.0.jar; 赠送原API文档:weixin-java-mp-3.5.0-javadoc.jar; 赠送源代码:weixin-java-mp-3.5.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-mp-3.5.0.pom; 包含翻译后的API...
赠送jar包:weixin-java-miniapp-2.8.0.jar; 赠送原API文档:weixin-java-miniapp-2.8.0-javadoc.jar; 赠送源代码:weixin-java-miniapp-2.8.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-miniapp-2.8.0....
赠送jar包:weixin-java-common-3.5.0.jar; 赠送原API文档:weixin-java-common-3.5.0-javadoc.jar; 赠送源代码:weixin-java-common-3.5.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-common-3.5.0.pom;...
赠送jar包:weixin-java-mp-2.8.0.jar; 赠送原API文档:weixin-java-mp-2.8.0-javadoc.jar; 赠送源代码:weixin-java-mp-2.8.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-mp-2.8.0.pom; 包含翻译后的API...
赠送jar包:weixin-java-pay-2.8.0.jar; 赠送原API文档:weixin-java-pay-2.8.0-javadoc.jar; 赠送源代码:weixin-java-pay-2.8.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-pay-2.8.0.pom; 包含翻译后...
赠送jar包:weixin-java-mp-3.5.0.jar; 赠送原API文档:weixin-java-mp-3.5.0-javadoc.jar; 赠送源代码:weixin-java-mp-3.5.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-mp-3.5.0.pom; 包含翻译后的API...
赠送jar包:weixin-java-pay-3.5.0.jar; 赠送原API文档:weixin-java-pay-3.5.0-javadoc.jar; 赠送源代码:weixin-java-pay-3.5.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-pay-3.5.0.pom; 包含翻译后...
weixin-popular 包括微信公众平台基础API与支付API,提供便捷的API调用接口. API 列表 TokenAPI access_token 获取 MediaAPI 多媒体上传下载(临时素材) MaterialAPI 永久素材 MenuAPI 菜单 MessageAPI 信息发送...
赠送jar包:weixin-java-common-3.5.0.jar; 赠送原API文档:weixin-java-common-3.5.0-javadoc.jar; 赠送源代码:weixin-java-common-3.5.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-common-3.5.0.pom;...
JFinal Weixin 是基于 JFinal 的微信公众号极速开发 SDK
微信 java weixin-java-tools-springmvc-master 微信 java weixin-java-tools-springmvc-master
标题中的"PyPI 官网下载 | weixin-python-0.4.3.tar.gz"指出这是一个从Python Package Index(PyPI)官方下载的资源,它是一个名为`weixin-python`的Python库的版本0.4.3。这个库通常包含了处理微信相关的功能,因为...
weixin-java-mp-demo-springboot, 微信公众号demo,使用weixin-java-tools,基于Spring Boot
weixin-java-mp -2.5.0和2.3.0的api说明文档,可以好好研究,封装了支付等接口
weixin803android1880_arm64.apk
标题中的“博客https://blog.csdn.net/weixin_49457347/article/details/1236所需文件”表明这是一个与特定博客文章相关的压缩包,但没有提供足够的信息来直接解释博客的内容。从描述中也无法获取更多细节,它只是...
weixin8024android2180_arm64.apk
backup_weixin8033android2320_arm64.apk
微信官方安装包weixin7021android1800_arm64.apk