Java編程調(diào)用微信接口實現(xiàn)圖文信息推送功能
本文實例講述了Java編程調(diào)用微信接口實現(xiàn)圖文信息等推送功能。分享給大家供大家參考,具體如下:
Java調(diào)用微信接口工具類,包含素材上傳、獲取素材列表、上傳圖文消息內(nèi)的圖片獲取URL、圖文信息推送。
微信圖文信息推送因注意html代碼字符串中將雙引號(")替換成單引號('),不然信息頁面中包含圖片將無法顯示且圖片后面的內(nèi)容也不會顯示
官方文檔: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("http://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 {
// 創(chuàng)建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);
// 設(shè)置請求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 當(dāng)有數(shù)據(jù)需要提交時
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意編碼格式,防止中文亂碼
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 將返回的輸入流轉(zhuǎn)換成字符串
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);
}
/**
* 把二進(jìn)制流轉(zhuǎn)化為byte字節(jié)數(shù)組
* @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一個文件對象用來保存圖片,默認(rèn)保存當(dāng)前工程根目錄
File imageFile = new File("mmbiz.png");
try {
//new一個URL對象
URL url = new URL(src);
//打開鏈接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//設(shè)置請求方式為"GET"
conn.setRequestMethod("GET");
//超時響應(yīng)時間為5秒
conn.setConnectTimeout(5 * 1000);
//通過輸入流獲取圖片數(shù)據(jù)
InputStream inStream = conn.getInputStream();
//得到圖片的二進(jìn)制數(shù)據(jù),以二進(jìn)制封裝得到數(shù)據(jù),具有通用性
byte[] data = readInputStream(inStream);
FileOutputStream outStream = new FileOutputStream(imageFile);
//寫入數(shù)據(jù)
outStream.write(data);
//關(guān)閉輸出流
outStream.close();
return imageFile;
} catch (Exception e) {
return imageFile;
}
}
/**
* 微信服務(wù)器素材上傳
* @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;
}
/**
* 微信服務(wù)器獲取素材列表
*/
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;
}
/**
* 上傳圖文消息內(nèi)的圖片獲取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("http://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");
}
}
更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java字符與字符串操作技巧總結(jié)》、《Java數(shù)組操作技巧總結(jié)》、《Java數(shù)學(xué)運算技巧總結(jié)》、《Java編碼操作技巧總結(jié)》和《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
Java利用釘釘機(jī)器人實現(xiàn)發(fā)送群消息
這篇文章主要為大家詳細(xì)介紹了Java語言如何通過釘釘機(jī)器人發(fā)送群消息通知,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-09-09
mybatis報錯?resultMapException的解決
這篇文章主要介紹了mybatis報錯?resultMapException的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
Java文件字符輸入流FileReader讀取txt文件亂碼的解決
這篇文章主要介紹了Java文件字符輸入流FileReader讀取txt文件亂碼的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09

