当前位置: 首页 > 编程笔记 >

Java编程调用微信接口实现图文信息推送功能

朱祺
2023-03-14
本文向大家介绍Java编程调用微信接口实现图文信息推送功能,包括了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算法相关内容感兴趣的读者可查看本站专题:《Java字符与字符串操作技巧总结》、《Java数组操作技巧总结》、《Java数学运算技巧总结》、《Java编码操作技巧总结》和《Java数据结构与算法教程》

希望本文所述对大家java程序设计有所帮助。

 类似资料:
  • 本文向大家介绍Python编程实现微信企业号文本消息推送功能示例,包括了Python编程实现微信企业号文本消息推送功能示例的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Python微信企业号文本消息推送功能。分享给大家供大家参考,具体如下: 企业号的创建、企业号应用的创建、组、tag、part就不赘述了,一搜一大堆,但是网上拿的那些个脚本好多都不好使,所以自己修了一个 坦率的讲,这个脚本

  • 本文向大家介绍java调用微信接口实现网页分享小功能,包括了java调用微信接口实现网页分享小功能的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了java调用微信接口实现网页分享小功能的具体代码,供大家参考,具体内容如下 // 获取access_token  *注意* 经过实际开发测试,微信分享不支持跨域请求,因此获取access_token的请求必须从服务器发起,否则无法获取到ac

  • 本文向大家介绍Python使用微信itchat接口实现查看自己微信的信息功能详解,包括了Python使用微信itchat接口实现查看自己微信的信息功能详解的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Python使用微信itchat接口实现查看自己微信的信息功能。分享给大家供大家参考,具体如下: itchat是python的一个api,可以访问自己的微信信息,功能还蛮好玩的,可以扒取朋友

  • 本文向大家介绍微信开发 消息推送实现代码,包括了微信开发 消息推送实现代码的使用技巧和注意事项,需要的朋友参考一下 最近做微信公共号的开发,有个需求是这样的消息推送,以文本的形式把编辑的消息发送给微信企业号中的某一个应用组,这里做下笔记,以下是整理内容: 根据当前日期 判断Access_Token 是否超期 如果超期返回新的Access_Token 否则返回之前的Access_Token 感谢阅读

  • 本文向大家介绍node.js微信小程序配置消息推送的实现,包括了node.js微信小程序配置消息推送的实现的使用技巧和注意事项,需要的朋友参考一下 在开发微信小程序时,有一个消息推送,它的解释是这样的。 消息推送具体的内容是下面的这个网址   https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/mess

  • 本文向大家介绍使用wxpy实现自动发送微信消息功能,包括了使用wxpy实现自动发送微信消息功能的使用技巧和注意事项,需要的朋友参考一下 思路整理:1、进入心灵鸡汤网页,使用python获取心灵鸡汤内容      2、登陆微信,找到需要发送的朋友      3、发送获取的内容 1、获取心灵鸡汤的内容   如下图,获取第一条鸡汤   实现如下: 2、登陆微信,搜索朋友,进行发送 其他发送类型格式: