Java编程调用微信接口实现图文信息推送功能
作者:sun1982fg 发布时间:2023-11-25 07:20:47
标签:Java,微信,推送
本文实例讲述了Java编程调用微信接口实现图文信息等推送功能。分享给大家供大家参考,具体如下:
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(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程序设计有所帮助。
来源:http://blog.csdn.net/sun1982fg/article/details/56012111


猜你喜欢
- Android的WebView做不到ios的WebView那样可以很方便的直接预览pdf文件。要实现利用WebView预览pdf我们可以使用
- 1. HTTP 响应码 301 和 302 代表的是什么?有什么区别?301:永久重定向。 302:暂时重定向。它们的区别是,301 对搜索
- java ,javaw 和 javaws 的区别:首先,所有的这些都是java的启动装置,java.e
- 前言近期有个业务需求,涉及用户付费相关的计算,需要一个日历组件,组件功能如下:仅支持从明天开始选择预定日期仅支持可选范围内的日期日期的选择是
- 1、JDK:Java Development Kit,java开发工具包。http://www.oracle.com/technetwork
- 1.Spring Gateway概述1.1 什么是Spring Cloud GatewaySpring Cloud Gateway是Spri
- Java二叉树排序算法排序二叉树的描述也是一个递归的描述, 所以排序二叉树的构造自然也用递归的:排序二叉树的3个特征:1:当前node的所有
- 1.问题描述在我引入SpringCloud-gateway,运行时报错如下:org.springframework.beans.factor
- SWF Tools 是一组用来处理 Flash 的 swf 文件的工具包,包括:1. 合并工具 swfcombine2. 抽取工具 swfe
- foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,colle
- 本文实例讲述了winform基于异步委托实现多线程摇奖器。分享给大家供大家参考。具体实现方法如下:using System;using Sy
- C#连接本地.mdf文件:项目中右键点击,新增——数据——基于服务的数据库,项目下直接生成.mdf数据库文件,后台(数据库的写入用参数传递)
- 博主第一次安装Android Studio 3.6版本的时候就找不到R.java文件,于是在网上找个各种方法,但是都没能解决问题。注意:本博
- 使用范围: 只能作用在方法和构造函数之上@SneakyThrows注解的作用得从java的异常设计体系说起。java中常见的异常有两种:Ex
- 0x01 创建要转换的类和主函数注意这里一定要实现序列化package day1; import java.io.Serializable;
- 为什么Android要申请权限简单说下在Android6.0及6.0以上一些google认为涉及“危险和用户隐私”的一些权限不仅要做清单文件
- Druid动态数据源配置 主要是继承AbstractRoutingDataSource再通过AOP来实现动态数据源切换.下面给大家介绍Dru
- poi导入纯数字等问题用poi导出excel时候,如果单元格设置纯数字,输入的数据一旦过大就是自动显示成科学记数法,导致导入后的数据出错,解
- RateLimiter官方文档RateLimiter令牌桶原理图随着时间流逝,系统会按恒定1/QPS时间间隔(如果QPS=100,则间隔是1
- 一直在使用Mybatis这个ORM框架,都是使用mybatis里的一些常用功能。今天在项目开发中有个业务是需要限制各个用户对某些表里的字段查