Java编程调用微信接口实现图文信息推送功能
本文实例讲述了Java编程调用微信接口实现图文信息等推送功能。分享给大家供大家参考,具体如下:
魏都ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联建站的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:028-86922220(备注:SSL证书合作)期待与您的合作!
Java调用微信接口工具类,包含素材上传、获取素材列表、上传图文消息内的图片获取URL、图文信息推送。
微信图文信息推送因注意html代码字符串中将双引号(")替换成单引号('),不然信息页面中包含图片将无法显示且图片后面的内容也不会显示
官方文档:http://mp.weixin.qq.com/wiki/home/
StringBuilder sb=new StringBuilder(); sb.append("{\"articles\":["); boolean t=false; for(MicroWechatInfo info:list){ if(t)sb.append(","); Pattern p = Pattern.compile("src\\s*=\\s*'(.*?)'",Pattern.CASE_INSENSITIVE); String content = info.getMicrowechatcontent().replace("\"", "'"); Matcher m = p.matcher(content); while (m.find()) { String[] str = m.group().split("'"); if(str.length>1){ try { if(!str[1].contains("//mmbiz.")){ content = content.replace(str[1], uploadImg(UrlToFile(str[1]),getAccessToken(wx.getAppid(), wx.getAppkey())).getString("url")); } } catch (Exception e) { } } } sb.append("{\"thumb_media_id\":\""+uploadMedia(new File(info.getMicrowechatcover()), getAccessToken(wx.getAppid(), wx.getAppkey()), "image").get("media_id")+"\"," + "\"author\":\""+info.getMicrowechatauthor()+"\"," + "\"title\":\""+info.getMicrowechattitle()+"\"," + "\"content_source_url\":\""+info.getOriginallink()+"\"," + "\"digest\":\""+info.getMicrowechatabstract()+"\"," + "\"show_cover_pic\":\""+info.getShowcover()+"\"," + "\"content\":\""+content+"\"}"); t=true; } sb.append("]}");
package com.xxx.frame.base.util; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; 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.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.PartSource; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.httpclient.protocol.Protocol; import com.google.gson.Gson; import com.xxx.frame.account.entity.MicroWechatAccount; import com.xxx.frame.account.entity.MicroWechatInfo; /** * 微信工具类 * @author hxt * */ public class WeixinUtil { public static String appid = "xxxxxxxxxxxxxxxxxxxxxxx"; public static String secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 素材上传(POST) private static final String UPLOAD_MEDIA = "https://api.weixin.qq.com/cgi-bin/material/add_material"; private static final String UPLOAD_IMG = "https://api.weixin.qq.com/cgi-bin/media/uploadimg"; private static final String BATCHGET_MATERIAL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material"; /** * 获得ACCESS_TOKEN * @param appid * @param secret * @return ACCESS_TOKEN */ public static String getAccessToken(String appid, String secret) { String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret; JSONObject jsonObject = httpRequest(url, "GET", null); try { if(jsonObject.getString("errcode")!=null){ return "false"; } }catch (Exception e) { } return jsonObject.getString("access_token"); } 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) { } catch (Exception e) { } return jsonObject; } /** * 获得getUserOpenIDs * @param accessToken * @return JSONObject */ public static JSONObject getUserOpenIDs(String accessToken) { String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken+"&next_openid="; return httpRequest(url, "GET", null); } /** * 把二进制流转化为byte字节数组 * @param instream * @return byte[] * @throws Exception */ public static byte[] readInputStream(InputStream instream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1204]; int len = 0; while ((len = instream.read(buffer)) != -1){ outStream.write(buffer,0,len); } instream.close(); return outStream.toByteArray(); } public static File UrlToFile(String src){ if(src.contains("http://wx.jinan.gov.cn")){ src = src.replace("http://wx.jinan.gov.cn", "C:"); System.out.println(src); return new File(src); } //new一个文件对象用来保存图片,默认保存当前工程根目录 File imageFile = new File("mmbiz.png"); try { //new一个URL对象 URL url = new URL(src); //打开链接 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //设置请求方式为"GET" conn.setRequestMethod("GET"); //超时响应时间为5秒 conn.setConnectTimeout(5 * 1000); //通过输入流获取图片数据 InputStream inStream = conn.getInputStream(); //得到图片的二进制数据,以二进制封装得到数据,具有通用性 byte[] data = readInputStream(inStream); FileOutputStream outStream = new FileOutputStream(imageFile); //写入数据 outStream.write(data); //关闭输出流 outStream.close(); return imageFile; } catch (Exception e) { return imageFile; } } /** * 微信服务器素材上传 * @param file 表单名称media * @param token access_token * @param type type只支持四种类型素材(video/image/voice/thumb) */ public static JSONObject uploadMedia(File file, String token, String type) { if(file==null||token==null||type==null){ return null; } if(!file.exists()){ return null; } String url = UPLOAD_MEDIA; JSONObject jsonObject = null; PostMethod post = new PostMethod(url); post.setRequestHeader("Connection", "Keep-Alive"); post.setRequestHeader("Cache-Control", "no-cache"); FilePart media = null; HttpClient httpClient = new HttpClient(); //信任任何类型的证书 Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); try { media = new FilePart("media", file); Part[] parts = new Part[] { new StringPart("access_token", token), new StringPart("type", type), media }; MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams()); post.setRequestEntity(entity); int status = httpClient.executeMethod(post); if (status == HttpStatus.SC_OK) { String text = post.getResponseBodyAsString(); jsonObject = JSONObject.fromObject(text); } else { } } catch (FileNotFoundException execption) { } catch (HttpException execption) { } catch (IOException execption) { } return jsonObject; } /** * 微信服务器获取素材列表 */ public static JSONObject batchgetMaterial(String appid, String secret,String type, int offset, int count) { try { return JSONObject.fromObject( new String(HttpsUtil.post(BATCHGET_MATERIAL+"?access_token="+ getAccessToken(appid, secret), "{\"type\":\""+type+"\",\"offset\":"+offset+",\"count\":"+count+"}", "UTF-8"), "UTF-8")); } catch (KeyManagementException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 上传图文消息内的图片获取URL * @param file 表单名称media * @param token access_token */ public static JSONObject uploadImg(File file, String token) { if(file==null||token==null){ return null; } if(!file.exists()){ return null; } String url = UPLOAD_IMG; JSONObject jsonObject = null; PostMethod post = new PostMethod(url); post.setRequestHeader("Connection", "Keep-Alive"); post.setRequestHeader("Cache-Control", "no-cache"); HttpClient httpClient = new HttpClient(); //信任任何类型的证书 Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); try { Part[] parts = new Part[] { new StringPart("access_token", token), new FilePart("media", file) }; MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams()); post.setRequestEntity(entity); int status = httpClient.executeMethod(post); if (status == HttpStatus.SC_OK) { String text = post.getResponseBodyAsString(); jsonObject = JSONObject.fromObject(text); } else { } } catch (FileNotFoundException execption) { } catch (HttpException execption) { } catch (IOException execption) { } return jsonObject; } /** * 图文信息推送 * @param list 图文信息列表 * @param wx 微信账号信息 */ public String send(Listlist,MicroWechatAccount wx){ StringBuilder sb=new StringBuilder(); sb.append("{\"articles\":["); boolean t=false; for(MicroWechatInfo info:list){ if(t)sb.append(","); Pattern p = Pattern.compile("src\\s*=\\s*'(.*?)'",Pattern.CASE_INSENSITIVE); String content = info.getMicrowechatcontent().replace("\"", "'"); Matcher m = p.matcher(content); while (m.find()) { String[] str = m.group().split("'"); if(str.length>1){ try { if(!str[1].contains("//mmbiz.")){ content = content.replace(str[1], uploadImg(UrlToFile(str[1]),getAccessToken(wx.getAppid(), wx.getAppkey())).getString("url")); } } catch (Exception e) { } } } sb.append("{\"thumb_media_id\":\""+uploadMedia(new File(info.getMicrowechatcover()), getAccessToken(wx.getAppid(), wx.getAppkey()), "image").get("media_id")+"\"," + "\"author\":\""+info.getMicrowechatauthor()+"\"," + "\"title\":\""+info.getMicrowechattitle()+"\"," + "\"content_source_url\":\""+info.getOriginallink()+"\"," + "\"digest\":\""+info.getMicrowechatabstract()+"\"," + "\"show_cover_pic\":\""+info.getShowcover()+"\"," + "\"content\":\""+content+"\"}"); t=true; } sb.append("]}"); JSONObject tt = httpRequest("https://api.weixin.qq.com/cgi-bin/material/add_news?access_token="+getAccessToken(wx.getAppid(), wx.getAppkey()), "POST", sb.toString()); JSONObject jo = getUserOpenIDs(getAccessToken(wx.getAppid(), wx.getAppkey())); String outputStr = "{\"touser\":"+jo.getJSONObject("data").getJSONArray("openid")+",\"msgtype\": \"mpnews\",\"mpnews\":{\"media_id\":\""+tt.getString("media_id")+"\"}}"; httpRequest("https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+getAccessToken(wx.getAppid(), wx.getAppkey()), "POST", outputStr); return tt.getString("media_id"); } }
更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java字符与字符串操作技巧总结》、《Java数组操作技巧总结》、《Java数学运算技巧总结》、《Java编码操作技巧总结》和《Java数据结构与算法教程》
希望本文所述对大家java程序设计有所帮助。
本文名称:Java编程调用微信接口实现图文信息推送功能
文章路径:http://ybzwz.com/article/picdoj.html