Java编程调用微信接口实现图文信息推送功能
程序员文章站
2024-02-24 09:53:28
本文实例讲述了java编程调用微信接口实现图文信息等推送功能。分享给大家供大家参考,具体如下:
java调用微信接口工具类,包含素材上传、获取素材列表、上传图文消息内的图...
本文实例讲述了java编程调用微信接口实现图文信息等推送功能。分享给大家供大家参考,具体如下:
java调用微信接口工具类,包含素材上传、获取素材列表、上传图文消息内的图片获取url、图文信息推送。
微信图文信息推送因注意html代码字符串中将双引号(")替换成单引号('),不然信息页面中包含图片将无法显示且图片后面的内容也不会显示
官方文档:
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(list<microwechatinfo> list,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程序设计有所帮助。