Java编程调用微信接口实现图文信息推送功能
本文实例讲述了Java编程调用微信接口实现图文信息等推送功能。分享给大家供大家参考,具体如下:
Java调用微信接口工具类,包含素材上传、获取素材列表、上传图文消息内的图片获取URL、图文信息推送。
微信图文信息推送因注意html代码字符串中将双引号(")替换成单引号('),不然信息页面中包含图片将无法显示且图片后面的内容也不会显示
官方文档:http://mp.weixin.qq.com/wiki/home/
StringBuildersb=newStringBuilder();
sb.append("{\"articles\":[");
booleant=false;
for(MicroWechatInfoinfo:list){
if(t)sb.append(",");
Patternp=Pattern.compile("src\\s*=\\s*'(.*?)'",Pattern.CASE_INSENSITIVE);
Stringcontent=info.getMicrowechatcontent().replace("\"","'");
Matcherm=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(Exceptione){
}
}
}
sb.append("{\"thumb_media_id\":\""+uploadMedia(newFile(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("]}");
packagecom.xxx.frame.base.util;
importjava.io.BufferedReader;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.io.UnsupportedEncodingException;
importjava.math.BigDecimal;
importjava.net.ConnectException;
importjava.net.HttpURLConnection;
importjava.net.MalformedURLException;
importjava.net.URISyntaxException;
importjava.net.URL;
importjava.security.KeyManagementException;
importjava.security.NoSuchAlgorithmException;
importjava.text.SimpleDateFormat;
importjava.util.ArrayList;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.List;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;
importjavax.net.ssl.HttpsURLConnection;
importjavax.net.ssl.SSLContext;
importjavax.net.ssl.SSLSocketFactory;
importjavax.net.ssl.TrustManager;
importnet.sf.json.JSONObject;
importorg.apache.commons.httpclient.HttpClient;
importorg.apache.commons.httpclient.HttpException;
importorg.apache.commons.httpclient.HttpStatus;
importorg.apache.commons.httpclient.methods.PostMethod;
importorg.apache.commons.httpclient.methods.multipart.FilePart;
importorg.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
importorg.apache.commons.httpclient.methods.multipart.Part;
importorg.apache.commons.httpclient.methods.multipart.PartSource;
importorg.apache.commons.httpclient.methods.multipart.StringPart;
importorg.apache.commons.httpclient.protocol.Protocol;
importcom.google.gson.Gson;
importcom.xxx.frame.account.entity.MicroWechatAccount;
importcom.xxx.frame.account.entity.MicroWechatInfo;
/**
*微信工具类
*@authorhxt
*
*/
publicclassWeixinUtil{
publicstaticStringappid="xxxxxxxxxxxxxxxxxxxxxxx";
publicstaticStringsecret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
//素材上传(POST)
privatestaticfinalStringUPLOAD_MEDIA="https://api.weixin.qq.com/cgi-bin/material/add_material";
privatestaticfinalStringUPLOAD_IMG="https://api.weixin.qq.com/cgi-bin/media/uploadimg";
privatestaticfinalStringBATCHGET_MATERIAL="https://api.weixin.qq.com/cgi-bin/material/batchget_material";
/**
*获得ACCESS_TOKEN
*@paramappid
*@paramsecret
*@returnACCESS_TOKEN
*/
publicstaticStringgetAccessToken(Stringappid,Stringsecret){
Stringurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
JSONObjectjsonObject=httpRequest(url,"GET",null);
try{
if(jsonObject.getString("errcode")!=null){
return"false";
}
}catch(Exceptione){
}
returnjsonObject.getString("access_token");
}
publicstaticJSONObjecthttpRequest(StringrequestUrl,StringrequestMethod,StringoutputStr){
JSONObjectjsonObject=null;
StringBufferbuffer=newStringBuffer();
try{
//创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[]tm={newMyX509TrustManager()};
SSLContextsslContext=SSLContext.getInstance("SSL","SunJSSE");
sslContext.init(null,tm,newjava.security.SecureRandom());
//从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactoryssf=sslContext.getSocketFactory();
URLurl=newURL(requestUrl);
HttpsURLConnectionhttpUrlConn=(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){
OutputStreamoutputStream=httpUrlConn.getOutputStream();
//注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//将返回的输入流转换成字符串
InputStreaminputStream=httpUrlConn.getInputStream();
InputStreamReaderinputStreamReader=newInputStreamReader(inputStream,"utf-8");
BufferedReaderbufferedReader=newBufferedReader(inputStreamReader);
Stringstr=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(ConnectExceptionce){
}catch(Exceptione){
}
returnjsonObject;
}
/**
*获得getUserOpenIDs
*@paramaccessToken
*@returnJSONObject
*/
publicstaticJSONObjectgetUserOpenIDs(StringaccessToken){
Stringurl="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken+"&next_openid=";
returnhttpRequest(url,"GET",null);
}
/**
*把二进制流转化为byte字节数组
*@paraminstream
*@returnbyte[]
*@throwsException
*/
publicstaticbyte[]readInputStream(InputStreaminstream)throwsException{
ByteArrayOutputStreamoutStream=newByteArrayOutputStream();
byte[]buffer=newbyte[1204];
intlen=0;
while((len=instream.read(buffer))!=-1){
outStream.write(buffer,0,len);
}
instream.close();
returnoutStream.toByteArray();
}
publicstaticFileUrlToFile(Stringsrc){
if(src.contains("http://wx.jinan.gov.cn")){
src=src.replace("http://wx.jinan.gov.cn","C:");
System.out.println(src);
returnnewFile(src);
}
//new一个文件对象用来保存图片,默认保存当前工程根目录
FileimageFile=newFile("mmbiz.png");
try{
//new一个URL对象
URLurl=newURL(src);
//打开链接
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时响应时间为5秒
conn.setConnectTimeout(5*1000);
//通过输入流获取图片数据
InputStreaminStream=conn.getInputStream();
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
byte[]data=readInputStream(inStream);
FileOutputStreamoutStream=newFileOutputStream(imageFile);
//写入数据
outStream.write(data);
//关闭输出流
outStream.close();
returnimageFile;
}catch(Exceptione){
returnimageFile;
}
}
/**
*微信服务器素材上传
*@paramfile表单名称media
*@paramtokenaccess_token
*@paramtypetype只支持四种类型素材(video/image/voice/thumb)
*/
publicstaticJSONObjectuploadMedia(Filefile,Stringtoken,Stringtype){
if(file==null||token==null||type==null){
returnnull;
}
if(!file.exists()){
returnnull;
}
Stringurl=UPLOAD_MEDIA;
JSONObjectjsonObject=null;
PostMethodpost=newPostMethod(url);
post.setRequestHeader("Connection","Keep-Alive");
post.setRequestHeader("Cache-Control","no-cache");
FilePartmedia=null;
HttpClienthttpClient=newHttpClient();
//信任任何类型的证书
Protocolmyhttps=newProtocol("https",newMySSLProtocolSocketFactory(),443);
Protocol.registerProtocol("https",myhttps);
try{
media=newFilePart("media",file);
Part[]parts=newPart[]{newStringPart("access_token",token),
newStringPart("type",type),media};
MultipartRequestEntityentity=newMultipartRequestEntity(parts,
post.getParams());
post.setRequestEntity(entity);
intstatus=httpClient.executeMethod(post);
if(status==HttpStatus.SC_OK){
Stringtext=post.getResponseBodyAsString();
jsonObject=JSONObject.fromObject(text);
}else{
}
}catch(FileNotFoundExceptionexecption){
}catch(HttpExceptionexecption){
}catch(IOExceptionexecption){
}
returnjsonObject;
}
/**
*微信服务器获取素材列表
*/
publicstaticJSONObjectbatchgetMaterial(Stringappid,Stringsecret,Stringtype,intoffset,intcount){
try{
returnJSONObject.fromObject(newString(HttpsUtil.post(BATCHGET_MATERIAL+"?access_token="+getAccessToken(appid,secret),"{\"type\":\""+type+"\",\"offset\":"+offset+",\"count\":"+count+"}","UTF-8"),"UTF-8"));
}catch(KeyManagementExceptione){
e.printStackTrace();
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returnnull;
}
/**
*上传图文消息内的图片获取URL
*@paramfile表单名称media
*@paramtokenaccess_token
*/
publicstaticJSONObjectuploadImg(Filefile,Stringtoken){
if(file==null||token==null){
returnnull;
}
if(!file.exists()){
returnnull;
}
Stringurl=UPLOAD_IMG;
JSONObjectjsonObject=null;
PostMethodpost=newPostMethod(url);
post.setRequestHeader("Connection","Keep-Alive");
post.setRequestHeader("Cache-Control","no-cache");
HttpClienthttpClient=newHttpClient();
//信任任何类型的证书
Protocolmyhttps=newProtocol("https",newMySSLProtocolSocketFactory(),443);
Protocol.registerProtocol("https",myhttps);
try{
Part[]parts=newPart[]{newStringPart("access_token",token),newFilePart("media",file)};
MultipartRequestEntityentity=newMultipartRequestEntity(parts,
post.getParams());
post.setRequestEntity(entity);
intstatus=httpClient.executeMethod(post);
if(status==HttpStatus.SC_OK){
Stringtext=post.getResponseBodyAsString();
jsonObject=JSONObject.fromObject(text);
}else{
}
}catch(FileNotFoundExceptionexecption){
}catch(HttpExceptionexecption){
}catch(IOExceptionexecption){
}
returnjsonObject;
}
/**
*图文信息推送
*@paramlist图文信息列表
*@paramwx微信账号信息
*/
publicStringsend(Listlist,MicroWechatAccountwx){
StringBuildersb=newStringBuilder();
sb.append("{\"articles\":[");
booleant=false;
for(MicroWechatInfoinfo:list){
if(t)sb.append(",");
Patternp=Pattern.compile("src\\s*=\\s*'(.*?)'",Pattern.CASE_INSENSITIVE);
Stringcontent=info.getMicrowechatcontent().replace("\"","'");
Matcherm=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(Exceptione){
}
}
}
sb.append("{\"thumb_media_id\":\""+uploadMedia(newFile(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("]}");
JSONObjecttt=httpRequest("https://api.weixin.qq.com/cgi-bin/material/add_news?access_token="+getAccessToken(wx.getAppid(),wx.getAppkey()),"POST",sb.toString());
JSONObjectjo=getUserOpenIDs(getAccessToken(wx.getAppid(),wx.getAppkey()));
StringoutputStr="{\"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);
returntt.getString("media_id");
}
}
更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java字符与字符串操作技巧总结》、《Java数组操作技巧总结》、《Java数学运算技巧总结》、《Java编码操作技巧总结》和《Java数据结构与算法教程》
希望本文所述对大家java程序设计有所帮助。