当前位置:   article > 正文

java公众号上传素材及发送图文消息实现_java weixin.mp 怎么上传素材

java weixin.mp 怎么上传素材

微信公众号先上传素材,再推送消息java代码实现:

首先公众号的图文消息是可以登录公众号,然后去管理--素材管理  下面去手动添加图文,图片,视频,音乐素材的.这样添加的素材属于永久素材.

用java代码实现的时候,很多人报错无效的media_id, 或无效的thumb_media_id,那是因为你上传的素材是临时的,换成永久id就可以了.

以下是我的几个亲测可用的Test.  具体的需求请参考官方文档 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1481187827_i0l21

1.获取素材列表

  1. package weixin.tuwen;
  2. import java.io.IOException;
  3. import java.security.KeyManagementException;
  4. import java.security.NoSuchAlgorithmException;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import weixin.tuwen.pojo.Material;
  8. import weixin.util.WX_HttpsUtil;
  9. import weixin.util.WX_TokenUtil;
  10. import com.alibaba.fastjson.JSONObject;
  11. import com.qs.util.HttpsPostUtil;
  12. import com.qs.util.httpspost.HttpsUtil;
  13. public class TestGetSucaiList {
  14. /**
  15. * 获取永久素材列表(根据分类)
  16. * 图片(image)、视频(video)、语音 (voice)、图文(news)
  17. * 参数:type offset count
  18. * @throws IOException
  19. * @throws NoSuchAlgorithmException
  20. * @throws KeyManagementException
  21. */
  22. public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException {
  23. String access_token = WX_TokenUtil.getWXToken().getAccessToken();
  24. String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+access_token;
  25. //POST请求发送的json参数
  26. Material m = new Material();
  27. m.setType("news");
  28. m.setOffset(0);
  29. m.setCount(10);
  30. JSONObject json = (JSONObject) JSONObject.toJSON(m);
  31. String str = json.toString();
  32. System.out.println(str);
  33. // Map<String,String> createMap = new HashMap<String,String>();
  34. // createMap.put("type","image");
  35. // createMap.put("offset","0");
  36. // createMap.put("count","1");
  37. byte[] result = HttpsUtil.post(url, str, "utf-8");
  38. String strs = new String(result);
  39. System.out.println(strs);
  40. }
  41. }

2.上传音乐素材到公众号  (有需要上传图片的,请自行把参数替换掉)

  1. package weixin.tuwen;
  2. import java.io.BufferedReader;
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. import java.io.OutputStream;
  10. import java.net.HttpURLConnection;
  11. import java.net.URL;
  12. import net.sf.json.JSONObject;
  13. import weixin.util.WX_TokenUtil;
  14. public class UploadSucai {
  15. /**
  16. * @param args
  17. * 上传音乐到公众号
  18. * 请求地址(post):https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN
  19. */
  20. public static void main(String[] args) {
  21. String access_token = WX_TokenUtil.getWXToken().getAccessToken();
  22. File file = new File("C:/Users/v_yiqqin/Music/asdasd.mp3");
  23. uploadPermanentMedia2(access_token,file,"测试标题","测试描述");
  24. }
  25. /**
  26. * 这里说下,在上传视频素材的时候,微信说不超过20M,我试了下,超过10M调通的可能性都比较小,建议大家上传视频素材的大小小于10M比交好
  27. * @param accessToken
  28. * @param file 上传的文件
  29. * @param title 上传类型为video的参数
  30. * @param introduction 上传类型为video的参数
  31. */
  32. public static void uploadPermanentMedia2(String accessToken,
  33. File file,String title,String introduction) {
  34. try {
  35. //这块是用来处理如果上传的类型是video的类型的
  36. JSONObject j=new JSONObject();
  37. j.put("title", title);
  38. j.put("introduction", introduction);
  39. // 拼装请求地址
  40. String uploadMediaUrl = "http://api.weixin.qq.com/cgi-bin/material/add_material?access_token=##ACCESS_TOKEN##";
  41. uploadMediaUrl = uploadMediaUrl.replace("##ACCESS_TOKEN##",accessToken);
  42. URL url = new URL(uploadMediaUrl);
  43. String result = null;
  44. long filelength = file.length();
  45. String fileName=file.getName();
  46. String suffix=fileName.substring(fileName.lastIndexOf("."),fileName.length());
  47. String type="voice/mp3"; //我这里写死
  48. /**
  49. * 你们需要在这里根据文件后缀suffix将type的值设置成对应的mime类型的值
  50. */
  51. HttpURLConnection con = (HttpURLConnection) url.openConnection();
  52. con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
  53. con.setDoInput(true);
  54. con.setDoOutput(true);
  55. con.setUseCaches(false); // post方式不能使用缓存
  56. // 设置请求头信息
  57. con.setRequestProperty("Connection", "Keep-Alive");
  58. con.setRequestProperty("Charset", "UTF-8");
  59. // 设置边界,这里的boundary是http协议里面的分割符,不懂的可惜百度(http 协议 boundary),这里boundary 可以是任意的值(111,2222)都行
  60. String BOUNDARY = "----------" + System.currentTimeMillis();
  61. con.setRequestProperty("Content-Type",
  62. "multipart/form-data; boundary=" + BOUNDARY);
  63. // 请求正文信息
  64. // 第一部分:
  65. StringBuilder sb = new StringBuilder();
  66. //这块是post提交type的值也就是文件对应的mime类型值
  67. sb.append("--"); // 必须多两道线 这里说明下,这两个横杠是http协议要求的,用来分隔提交的参数用的,不懂的可以看看http 协议头
  68. sb.append(BOUNDARY);
  69. sb.append("\r\n");
  70. sb.append("Content-Disposition: form-data;name=\"type\" \r\n\r\n"); //这里是参数名,参数名和值之间要用两次
  71. sb.append(type+"\r\n"); //参数的值
  72. //这块是上传video是必须的参数,你们可以在这里根据文件类型做if/else 判断
  73. sb.append("--"); // 必须多两道线
  74. sb.append(BOUNDARY);
  75. sb.append("\r\n");
  76. sb.append("Content-Disposition: form-data;name=\"description\" \r\n\r\n");
  77. sb.append(j.toString()+"\r\n");
  78. /**
  79. * 这里重点说明下,上面两个参数完全可以卸载url地址后面 就想我们平时url地址传参一样,
  80. * http://api.weixin.qq.com/cgi-bin/material/add_material?access_token=##ACCESS_TOKEN##&type=""&description={} 这样,如果写成这样,上面的
  81. * 那两个参数的代码就不用写了,不过media参数能否这样提交我没有试,感兴趣的可以试试
  82. */
  83. sb.append("--"); // 必须多两道线
  84. sb.append(BOUNDARY);
  85. sb.append("\r\n");
  86. //这里是media参数相关的信息,这里是否能分开下我没有试,感兴趣的可以试试
  87. sb.append("Content-Disposition: form-data;name=\"media\";filename=\""
  88. + fileName + "\";filelength=\"" + filelength + "\" \r\n");
  89. sb.append("Content-Type:application/octet-stream\r\n\r\n");
  90. System.out.println(sb.toString());
  91. byte[] head = sb.toString().getBytes("utf-8");
  92. // 获得输出流
  93. OutputStream out = new DataOutputStream(con.getOutputStream());
  94. // 输出表头
  95. out.write(head);
  96. // 文件正文部分
  97. // 把文件已流文件的方式 推入到url中
  98. DataInputStream in = new DataInputStream(new FileInputStream(file));
  99. int bytes = 0;
  100. byte[] bufferOut = new byte[1024];
  101. while ((bytes = in.read(bufferOut)) != -1) {
  102. out.write(bufferOut, 0, bytes);
  103. }
  104. in.close();
  105. // 结尾部分,这里结尾表示整体的参数的结尾,结尾要用"--"作为结束,这些都是http协议的规定
  106. byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
  107. out.write(foot);
  108. out.flush();
  109. out.close();
  110. StringBuffer buffer = new StringBuffer();
  111. BufferedReader reader = null;
  112. // 定义BufferedReader输入流来读取URL的响应
  113. reader = new BufferedReader(new InputStreamReader(
  114. con.getInputStream()));
  115. String line = null;
  116. while ((line = reader.readLine()) != null) {
  117. buffer.append(line);
  118. }
  119. if (result == null) {
  120. result = buffer.toString();
  121. }
  122. // 使用JSON-lib解析返回结果
  123. JSONObject jsonObject = JSONObject.fromObject(result);
  124. if (jsonObject.has("media_id")) {
  125. System.out.println("media_id:"+jsonObject.getString("media_id"));
  126. } else {
  127. System.out.println(jsonObject.toString());
  128. }
  129. System.out.println("json:"+jsonObject.toString());
  130. } catch (IOException e) {
  131. e.printStackTrace();
  132. } finally {
  133. }
  134. }
  135. }

 

3.上传临时 或者 永久缩略图素材 (注释掉的地址是临时素材的)

 

  1. package weixin.tuwen;
  2. import java.io.BufferedReader;
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.InputStreamReader;
  10. import java.io.OutputStream;
  11. import java.net.HttpURLConnection;
  12. import java.net.URL;
  13. import net.sf.json.JSONObject;
  14. import weixin.util.WX_TokenUtil;
  15. public class UploadLinshiSucai {
  16. //临时素材地址
  17. // private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
  18. //永久素材的地址
  19. private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE";
  20. public static String uploadFile(File file, String accessToken, String type) throws Exception{
  21. // File file = new File(filePath);
  22. if(!file.exists() || !file.isFile()) {
  23. throw new IOException("文件不存在!");
  24. }
  25. String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
  26. URL urlObj = new URL(url);
  27. //连接
  28. HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
  29. conn.setRequestMethod("POST");
  30. conn.setDoInput(true);
  31. conn.setDoOutput(true);
  32. conn.setUseCaches(false);
  33. //请求头
  34. conn.setRequestProperty("Connection", "Keep-Alive");
  35. conn.setRequestProperty("Charset", "UTF-8");
  36. //conn.setRequestProperty("Content-Type","multipart/form-data;");
  37. //设置边界
  38. String BOUNDARY = "----------" + System.currentTimeMillis();
  39. conn.setRequestProperty("Content-Type","multipart/form-data;boundary="+BOUNDARY);
  40. StringBuilder sb = new StringBuilder();
  41. sb.append("--");
  42. sb.append(BOUNDARY);
  43. sb.append("\r\n");
  44. sb.append("Content-Disposition:form-data;name=\"file\";filename=\""+file.getName()+"\"\r\n");
  45. sb.append("Content-Type:application/octet-stream\r\n\r\n");
  46. byte[] head = sb.toString().getBytes("utf-8");
  47. //输出流
  48. OutputStream out = new DataOutputStream(conn.getOutputStream());
  49. out.write(head);
  50. //文件正文部分
  51. DataInputStream in = new DataInputStream(new FileInputStream(file));
  52. int bytes = 0;
  53. byte[] bufferOut = new byte[1024];
  54. while((bytes = in.read(bufferOut))!=-1) {
  55. out.write(bufferOut,0,bytes);
  56. }
  57. in.close();
  58. //结尾
  59. byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
  60. out.write(foot);
  61. out.flush();
  62. out.close();
  63. //获取响应
  64. StringBuffer buffer = new StringBuffer();
  65. BufferedReader reader = null;
  66. String result = null;
  67. reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  68. String line = null;
  69. while((line = reader.readLine()) != null) {
  70. buffer.append(line);
  71. }
  72. if(result == null) {
  73. result = buffer.toString();
  74. }
  75. reader.close();
  76. //需要添加json-lib jar包
  77. JSONObject json = JSONObject.fromObject(result);
  78. System.out.println(json);
  79. String mediaId = json.getString("thumb_media_id");
  80. return mediaId;
  81. }
  82. public static void main(String[] args) throws Exception {
  83. String access_token = WX_TokenUtil.getWXToken().getAccessToken();
  84. File file = new File("C:/Users/Music/timg.jpg");
  85. String type = "thumb";
  86. uploadFile(file,access_token,type);
  87. }
  88. }

4.上传图文消息素材

  1. package weixin.tuwen;
  2. import java.io.IOException;
  3. import java.security.KeyManagementException;
  4. import java.security.NoSuchAlgorithmException;
  5. import com.alibaba.fastjson.JSONObject;
  6. import com.qs.util.httpspost.HttpsUtil;
  7. import weixin.tuwen.pojo.Tuwen;
  8. import weixin.util.WX_TokenUtil;
  9. /**
  10. * 上传图文消息素材【订阅号与服务号认证后均可用】
  11. * http请求方式: POST
  12. https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN
  13. * @author v_yiqqin
  14. */
  15. public class TuwenUpload {
  16. public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException{
  17. String access_token = WX_TokenUtil.getWXToken().getAccessToken();
  18. // System.out.println(access_token);
  19. // String url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token="+access_token;
  20. //永久素材地址
  21. String url = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token="+access_token;
  22. Tuwen tt = new Tuwen();
  23. tt.setThumb_media_id("aprI7dnR4XeWcPEJcjLeIUjcDJv658pne4-2FUzEb6A");
  24. tt.setAuthor("kevin");
  25. tt.setTitle("图文测试66666");
  26. tt.setContent_source_url("www.baidu.com");
  27. tt.setContent("测试内容666666");
  28. tt.setDigest("描述666666");
  29. tt.setShow_cover_pic(1);
  30. JSONObject json = (JSONObject) JSONObject.toJSON(tt);
  31. String str = json.toString();
  32. str = "{"+"\"articles\":["+str+"]"+"}";
  33. byte[] result = HttpsUtil.post(url, str, "utf-8");
  34. String strs = new String(result);
  35. System.out.println(strs);
  36. }
  37. }

5.最后一步,发送图文消息

  1. package weixin.tuwen;
  2. import java.io.IOException;
  3. import java.security.KeyManagementException;
  4. import java.security.NoSuchAlgorithmException;
  5. import java.util.List;
  6. import com.alibaba.fastjson.JSONObject;
  7. import com.qs.util.httpspost.HttpsUtil;
  8. import weixin.tuwen.pojo.GetUserList;
  9. import weixin.tuwen.pojo.Media_id;
  10. import weixin.tuwen.pojo.SendPojo;
  11. import weixin.tuwen.pojo.Text;
  12. import weixin.util.WX_TokenUtil;
  13. public class SendMessage {
  14. /**
  15. * @param args
  16. * @throws IOException
  17. * @throws NoSuchAlgorithmException
  18. * @throws KeyManagementException
  19. */
  20. public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException {
  21. String access_token = WX_TokenUtil.getWXToken().getAccessToken();
  22. String url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+access_token;
  23. //先获取用户openid列表
  24. List userList = GetUserList.getUserList();
  25. String openid = userList.toString();
  26. System.out.println(openid);
  27. Media_id m = new Media_id();
  28. m.setMedia_id("aprI7dnR4XasdsafdghjewetrsdKiawoXw6RFzGM");
  29. JSONObject json1 = (JSONObject) JSONObject.toJSON(m);
  30. String str1 = json1.toString();
  31. System.out.println(str1);
  32. //封装请求参数
  33. SendPojo sp = new SendPojo();
  34. sp.setTouser(userList);
  35. sp.setMpnews(str1);
  36. sp.setMsgtype("mpnews");
  37. sp.setSend_ignore_reprint(0);
  38. // Text t = new Text();
  39. // t.setContent("hello from boxer");
  40. // JSONObject json1 = (JSONObject) JSONObject.toJSON(t);
  41. // String str1 = json1.toString();
  42. // System.out.println(str1);
  43. //
  44. // SendPojo sp = new SendPojo();
  45. // sp.setTouser(userList);
  46. // sp.setMsgtype("text");
  47. // sp.setText(str1);
  48. //
  49. JSONObject json = (JSONObject) JSONObject.toJSON(sp);
  50. String str = json.toString();
  51. str= str.replace("\\", "");
  52. str= str.replace("\"{", "{");
  53. str= str.replace("}\"", "}");
  54. System.out.println(str);
  55. byte[] result = HttpsUtil.post(url, str, "utf-8");
  56. String strs = new String(result);
  57. System.out.println(strs);
  58. }
  59. }

6.获取用户列表(群发用户)

  1. package weixin.tuwen.pojo;
  2. import java.util.List;
  3. import com.alibaba.fastjson.JSONObject;
  4. import weixin.util.WX_HttpsUtil;
  5. import weixin.util.WX_TokenUtil;
  6. public class GetUserList {
  7. /**
  8. * @param args
  9. */
  10. public static List getUserList() {
  11. String access_token = WX_TokenUtil.getWXToken().getAccessToken();
  12. String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token;
  13. JSONObject result = WX_HttpsUtil.httpsRequest(url, "GET",null);
  14. JSONObject resultJson = new JSONObject(result);
  15. JSONObject data = (JSONObject) resultJson.get("data");
  16. List openidlist = (List) data.get("openid");
  17. return openidlist;
  18. }
  19. }

如果任何疑问或学习交流,请搜索公众号"老秦的快乐生活"获取我的联系方式

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/70817
推荐阅读
相关标签
  

闽ICP备14008679号