JAVA调用微信接口(包含图文信息推送)

  1. StringBuilder sb=new StringBuilder();  
  2. sb.append("{\"articles\":[");  
  3. boolean t=false;  
  4. for(MicroWechatInfo info:list){  
  5.     if(t)sb.append(",");  
  6.     Pattern p = Pattern.compile("src\\s*=\\s*'(.*?)'",Pattern.CASE_INSENSITIVE);  
  7.     String content = info.getMicrowechatcontent().replace("\"", "'");  
  8.     Matcher m = p.matcher(content);  
  9.     while (m.find()) {  
  10.         String[] str = m.group().split("'");  
  11.         if(str.length>1){  
  12.             try {  
  13.                 if(!str[1].contains("//mmbiz.")){  
  14.                     content = content.replace(str[1], uploadImg(UrlToFile(str[1]),getAccessToken(wx.getAppid(), wx.getAppkey())).getString("url"));  
  15.                 }  
  16.             } catch (Exception e) {  
  17.             }  
  18.         }  
  19.     }  
  20.     sb.append("{\"thumb_media_id\":\""+uploadMedia(new File(info.getMicrowechatcover()), getAccessToken(wx.getAppid(), wx.getAppkey()), "image").get("media_id")+"\"," +  
  21.             "\"author\":\""+info.getMicrowechatauthor()+"\"," +  
  22.             "\"title\":\""+info.getMicrowechattitle()+"\"," +  
  23.             "\"content_source_url\":\""+info.getOriginallink()+"\"," +  
  24.             "\"digest\":\""+info.getMicrowechatabstract()+"\"," +  
  25.             "\"show_cover_pic\":\""+info.getShowcover()+"\"," +  
  26.             "\"content\":\""+content+"\"}");  
  27.     t=true;  
  28. }  

  1. sb.append("]}");  

  1. package com.xxx.frame.base.util;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.InputStreamReader;  
  11. import java.io.OutputStream;  
  12. import java.io.UnsupportedEncodingException;  
  13. import java.math.BigDecimal;  
  14. import java.net.ConnectException;  
  15. import java.net.HttpURLConnection;  
  16. import java.net.MalformedURLException;  
  17. import java.net.URISyntaxException;  
  18. import java.net.URL;  
  19. import java.security.KeyManagementException;  
  20. import java.security.NoSuchAlgorithmException;  
  21. import java.text.SimpleDateFormat;  
  22. import java.util.ArrayList;  
  23. import java.util.Date;  
  24. import java.util.HashMap;  
  25. import java.util.List;  
  26. import java.util.regex.Matcher;  
  27. import java.util.regex.Pattern;  
  28.   
  29. import javax.net.ssl.HttpsURLConnection;  
  30. import javax.net.ssl.SSLContext;  
  31. import javax.net.ssl.SSLSocketFactory;  
  32. import javax.net.ssl.TrustManager;  
  33.   
  34. import net.sf.json.JSONObject;  
  35.   
  36. import org.apache.commons.httpclient.HttpClient;  
  37. import org.apache.commons.httpclient.HttpException;  
  38. import org.apache.commons.httpclient.HttpStatus;  
  39. import org.apache.commons.httpclient.methods.PostMethod;  
  40. import org.apache.commons.httpclient.methods.multipart.FilePart;  
  41. import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;  
  42. import org.apache.commons.httpclient.methods.multipart.Part;  
  43. import org.apache.commons.httpclient.methods.multipart.PartSource;  
  44. import org.apache.commons.httpclient.methods.multipart.StringPart;  
  45. import org.apache.commons.httpclient.protocol.Protocol;  
  46.   
  47. import com.google.gson.Gson;  
  48. import com.xxx.frame.account.entity.MicroWechatAccount;  
  49. import com.xxx.frame.account.entity.MicroWechatInfo;  
  50. /** 
  51.  * 微信工具类 
  52.  * @author hxt 
  53.  * 
  54.  */  
  55. public class WeixinUtil {  
  56.     public static String appid = "xxxxxxxxxxxxxxxxxxxxxxx";  
  57.     public static String secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";  
  58.       
  59.     // 素材上传(POST)  
  60.     private static final String UPLOAD_MEDIA = "https://api.weixin.qq.com/cgi-bin/material/add_material";  
  61.     private static final String UPLOAD_IMG = "https://api.weixin.qq.com/cgi-bin/media/uploadimg";  
  62.       
  63.     private static final String BATCHGET_MATERIAL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material";  
  64.     /** 
  65.      * 获得ACCESS_TOKEN 
  66.      * @param appid 
  67.      * @param secret 
  68.      * @return ACCESS_TOKEN 
  69.      */  
  70.     public static String getAccessToken(String appid, String secret) {  
  71.         String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;  
  72.         JSONObject jsonObject = httpRequest(url, "GET"null);    
  73.         try {  
  74.             if(jsonObject.getString("errcode")!=null){  
  75.                 return "false";  
  76.             }  
  77.         }catch (Exception e) {  
  78.         }  
  79.         return jsonObject.getString("access_token");  
  80.     }  
  81.       
  82.     public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {  
  83.         JSONObject jsonObject = null;  
  84.         StringBuffer buffer = new StringBuffer();  
  85.         try {  
  86.             // 创建SSLContext对象,并使用我们指定的信任管理器初始化  
  87.             TrustManager[] tm = { new MyX509TrustManager() };  
  88.             SSLContext sslContext = SSLContext.getInstance("SSL""SunJSSE");  
  89.             sslContext.init(null, tm, new java.security.SecureRandom());  
  90.             // 从上述SSLContext对象中得到SSLSocketFactory对象  
  91.             SSLSocketFactory ssf = sslContext.getSocketFactory();  
  92.   
  93.             URL url = new URL(requestUrl);  
  94.             HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
  95.             httpUrlConn.setSSLSocketFactory(ssf);  
  96.   
  97.             httpUrlConn.setDoOutput(true);  
  98.             httpUrlConn.setDoInput(true);  
  99.             httpUrlConn.setUseCaches(false);  
  100.             // 设置请求方式(GET/POST)  
  101.             httpUrlConn.setRequestMethod(requestMethod);  
  102.   
  103.             if ("GET".equalsIgnoreCase(requestMethod))  
  104.                 httpUrlConn.connect();  
  105.   
  106.             // 当有数据需要提交时  
  107.             if (null != outputStr) {  
  108.                 OutputStream outputStream = httpUrlConn.getOutputStream();  
  109.                 // 注意编码格式,防止中文乱码  
  110.                 outputStream.write(outputStr.getBytes("UTF-8"));  
  111.                 outputStream.close();  
  112.             }  
  113.   
  114.             // 将返回的输入流转换成字符串  
  115.             InputStream inputStream = httpUrlConn.getInputStream();  
  116.             InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
  117.             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  118.   
  119.             String str = null;  
  120.             while ((str = bufferedReader.readLine()) != null) {  
  121.                 buffer.append(str);  
  122.             }  
  123.             bufferedReader.close();  
  124.             inputStreamReader.close();  
  125.             // 释放资源  
  126.             inputStream.close();  
  127.             inputStream = null;  
  128.             httpUrlConn.disconnect();  
  129.             jsonObject = JSONObject.fromObject(buffer.toString());  
  130.         } catch (ConnectException ce) {  
  131.         } catch (Exception e) {  
  132.         }  
  133.         return jsonObject;  
  134.     }  
  135.       
  136.     /** 
  137.      * 获得getUserOpenIDs 
  138.      * @param accessToken 
  139.      * @return JSONObject 
  140.      */  
  141.     public static JSONObject getUserOpenIDs(String accessToken) {  
  142.         String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken+"&next_openid=";  
  143.         return httpRequest(url, "GET"null);  
  144.     }  
  145.       
  146.     /**  
  147.      * 把二进制流转化为byte字节数组  
  148.      * @param instream  
  149.      * @return byte[]  
  150.      * @throws Exception  
  151.      */    
  152.     public static byte[] readInputStream(InputStream instream) throws Exception {    
  153.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();    
  154.         byte[]  buffer = new byte[1204];    
  155.         int len = 0;    
  156.         while ((len = instream.read(buffer)) != -1){    
  157.             outStream.write(buffer,0,len);    
  158.         }    
  159.         instream.close();    
  160.         return outStream.toByteArray();             
  161.     }    
  162.       
  163.     public static File UrlToFile(String src){  
  164.         if(src.contains("http://wx.jinan.gov.cn")){  
  165.             src = src.replace("http://wx.jinan.gov.cn""C:");  
  166.             System.out.println(src);  
  167.             return new File(src);  
  168.         }  
  169.           
  170.         //new一个文件对象用来保存图片,默认保存当前工程根目录    
  171.         File imageFile = new File("mmbiz.png");  
  172.         try {  
  173.             //new一个URL对象    
  174.             URL url = new URL(src);    
  175.             //打开链接    
  176.             HttpURLConnection conn = (HttpURLConnection)url.openConnection();    
  177.             //设置请求方式为"GET"    
  178.             conn.setRequestMethod("GET");    
  179.             //超时响应时间为5秒    
  180.             conn.setConnectTimeout(5 * 1000);    
  181.             //通过输入流获取图片数据    
  182.             InputStream inStream = conn.getInputStream();    
  183.             //得到图片的二进制数据,以二进制封装得到数据,具有通用性    
  184.             byte[] data = readInputStream(inStream);    
  185.             FileOutputStream outStream = new FileOutputStream(imageFile);    
  186.             //写入数据    
  187.             outStream.write(data);    
  188.             //关闭输出流    
  189.             outStream.close();    
  190.             return imageFile;  
  191.         } catch (Exception e) {  
  192.             return imageFile;  
  193.         }  
  194.     }    
  195.       
  196.     /** 
  197.      * 微信服务器素材上传 
  198.      * @param file  表单名称media 
  199.      * @param token access_token 
  200.      * @param type  type只支持四种类型素材(video/image/voice/thumb) 
  201.      */  
  202.     public static JSONObject uploadMedia(File file, String token, String type) {  
  203.         if(file==null||token==null||type==null){  
  204.             return null;  
  205.         }  
  206.         if(!file.exists()){  
  207.             return null;  
  208.         }  
  209.         String url = UPLOAD_MEDIA;  
  210.         JSONObject jsonObject = null;  
  211.         PostMethod post = new PostMethod(url);  
  212.         post.setRequestHeader("Connection""Keep-Alive");  
  213.         post.setRequestHeader("Cache-Control""no-cache");  
  214.         FilePart media = null;  
  215.         HttpClient httpClient = new HttpClient();  
  216.         //信任任何类型的证书  
  217.         Protocol myhttps = new Protocol("https"new MySSLProtocolSocketFactory(), 443);   
  218.         Protocol.registerProtocol("https", myhttps);  
  219.   
  220.         try {  
  221.             media = new FilePart("media", file);  
  222.             Part[] parts = new Part[] { new StringPart("access_token", token),  
  223.                     new StringPart("type", type), media };  
  224.             MultipartRequestEntity entity = new MultipartRequestEntity(parts,  
  225.                     post.getParams());  
  226.             post.setRequestEntity(entity);  
  227.             int status = httpClient.executeMethod(post);  
  228.             if (status == HttpStatus.SC_OK) {  
  229.                 String text = post.getResponseBodyAsString();  
  230.                 jsonObject = JSONObject.fromObject(text);  
  231.             } else {  
  232.             }  
  233.         } catch (FileNotFoundException execption) {  
  234.         } catch (HttpException execption) {  
  235.         } catch (IOException execption) {  
  236.         }  
  237.         return jsonObject;  
  238.     }  
  239.       
  240.     /** 
  241.      * 微信服务器获取素材列表 
  242.      */  
  243.     public static JSONObject batchgetMaterial(String appid, String secret,String type, int offset, int count) {  
  244.         try {  
  245.             return JSONObject.fromObject( new String(HttpsUtil.post(BATCHGET_MATERIAL+"?access_token="+ getAccessToken(appid, secret), "{\"type\":\""+type+"\",\"offset\":"+offset+",\"count\":"+count+"}""UTF-8"), "UTF-8"));  
  246.         } catch (KeyManagementException e) {  
  247.             e.printStackTrace();  
  248.         } catch (UnsupportedEncodingException e) {  
  249.             e.printStackTrace();  
  250.         } catch (NoSuchAlgorithmException e) {  
  251.             e.printStackTrace();  
  252.         } catch (IOException e) {  
  253.             e.printStackTrace();  
  254.         }  
  255.         return null;  
  256.     }  
  257.       
  258.     /** 
  259.      * 上传图文消息内的图片获取URL 
  260.      * @param file  表单名称media 
  261.      * @param token access_token 
  262.      */  
  263.     public static JSONObject uploadImg(File file, String token) {  
  264.         if(file==null||token==null){  
  265.             return null;  
  266.         }  
  267.         if(!file.exists()){  
  268.             return null;  
  269.         }  
  270.         String url = UPLOAD_IMG;  
  271.         JSONObject jsonObject = null;  
  272.         PostMethod post = new PostMethod(url);  
  273.         post.setRequestHeader("Connection""Keep-Alive");  
  274.         post.setRequestHeader("Cache-Control""no-cache");  
  275.         HttpClient httpClient = new HttpClient();  
  276.         //信任任何类型的证书  
  277.         Protocol myhttps = new Protocol("https"new MySSLProtocolSocketFactory(), 443);   
  278.         Protocol.registerProtocol("https", myhttps);  
  279.   
  280.         try {  
  281.             Part[] parts = new Part[] { new StringPart("access_token", token), new FilePart("media", file) };  
  282.             MultipartRequestEntity entity = new MultipartRequestEntity(parts,  
  283.                     post.getParams());  
  284.             post.setRequestEntity(entity);  
  285.             int status = httpClient.executeMethod(post);  
  286.             if (status == HttpStatus.SC_OK) {  
  287.                 String text = post.getResponseBodyAsString();  
  288.                 jsonObject = JSONObject.fromObject(text);  
  289.             } else {  
  290.             }  
  291.         } catch (FileNotFoundException execption) {  
  292.         } catch (HttpException execption) {  
  293.         } catch (IOException execption) {  
  294.         }  
  295.         return jsonObject;  
  296.     }  
  297.       
  298.     /** 
  299.      * 图文信息推送 
  300.      * @param list  图文信息列表 
  301.      * @param wx 微信账号信息 
  302.      */  
  303.     public String send(List list,MicroWechatAccount wx){  
  304.         StringBuilder sb=new StringBuilder();  
  305.         sb.append("{\"articles\":[");  
  306.         boolean t=false;  
  307.         for(MicroWechatInfo info:list){  
  308.             if(t)sb.append(",");  
  309.             Pattern p = Pattern.compile("src\\s*=\\s*'(.*?)'",Pattern.CASE_INSENSITIVE);  
  310.             String content = info.getMicrowechatcontent().replace("\"""'");  
  311.             Matcher m = p.matcher(content);  
  312.             while (m.find()) {  
  313.                 String[] str = m.group().split("'");  
  314.                 if(str.length>1){  
  315.                     try {  
  316.                         if(!str[1].contains("//mmbiz.")){  
  317.                             content = content.replace(str[1], uploadImg(UrlToFile(str[1]),getAccessToken(wx.getAppid(), wx.getAppkey())).getString("url"));  
  318.                         }  
  319.                     } catch (Exception e) {  
  320.                     }  
  321.                 }  
  322.             }  
  323.             sb.append("{\"thumb_media_id\":\""+uploadMedia(new File(info.getMicrowechatcover()), getAccessToken(wx.getAppid(), wx.getAppkey()), "image").get("media_id")+"\"," +  
  324.                     "\"author\":\""+info.getMicrowechatauthor()+"\"," +  
  325.                     "\"title\":\""+info.getMicrowechattitle()+"\"," +  
  326.                     "\"content_source_url\":\""+info.getOriginallink()+"\"," +  
  327.                     "\"digest\":\""+info.getMicrowechatabstract()+"\"," +  
  328.                     "\"show_cover_pic\":\""+info.getShowcover()+"\"," +  
  329.                     "\"content\":\""+content+"\"}");  
  330.             t=true;  
  331.         }  
  332.         sb.append("]}");  
  333.         JSONObject tt = httpRequest("https://api.weixin.qq.com/cgi-bin/material/add_news?access_token="+getAccessToken(wx.getAppid(), wx.getAppkey()), "POST", sb.toString());  
  334.         JSONObject jo = getUserOpenIDs(getAccessToken(wx.getAppid(), wx.getAppkey()));  
  335.         String outputStr = "{\"touser\":"+jo.getJSONObject("data").getJSONArray("openid")+",\"msgtype\": \"mpnews\",\"mpnews\":{\"media_id\":\""+tt.getString("media_id")+"\"}}";  
  336.         httpRequest("https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+getAccessToken(wx.getAppid(), wx.getAppkey()), "POST", outputStr);  
  337.         return tt.getString("media_id");  
  338.     }  
  339.       
  340. }  



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值