服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|

服务器之家 - 编程语言 - JAVA教程 - Java编程调用微信接口实现图文信息推送功能

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

2020-12-19 13:52sun1982fg JAVA教程

这篇文章主要介绍了Java编程调用微信接口实现图文信息等推送功能,涉及java微信图文信息推送接口调用及相关文件、字符串编码转换相关操作技巧,需要的朋友可以参考下

本文实例讲述了Java编程调用微信接口实现图文信息等推送功能。分享给大家供大家参考,具体如下:

Java调用微信接口工具类,包含素材上传、获取素材列表、上传图文消息内的图片获取URL、图文信息推送。

微信图文信息推送因注意html代码字符串中将双引号(")替换成单引号('),不然信息页面中包含图片将无法显示且图片后面的内容也不会显示

官方文档:http://mp.weixin.qq.com/wiki/home/

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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("]}");
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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

延伸 · 阅读

精彩推荐