文章目录

  • 代码业务场景

    一、前提操作

    二、开始操作

    1.获取公众号的开发者id(AppID)和开发者密码(AppSecret),以及设置IP白名单

    2.代码操作

    总结


代码业务场景

最近在给客户开发一款小程序,然后客户还有自己运营的公众号,想要把公众号里面发布的一些内容能够同步到小程序里面进行展示。如下所示,获取公众号里面的发表记录→发布→发表成功的文章内容,删除的内容是获取不到的。

一、介绍

开始翻了下微信公众号的开发文档,其实文档里面些的很清楚,怎么访问,怎么获取,怎么解析写的一清二处,不清楚的同学可以看下链接:微信开放平台公众号开发文档
看了下网上说的一些还要公众号绑定小程序,其实如果只是单纯的获取公众号里面的文章信息的话,是不需要绑定的,如果要在小程序里面打开公众号返回的文章url的话,才需要绑定。

二、开始操作

1.获取公众号的开发者id(AppID)和开发者密码(AppSecret),以及设置IP白名单

登录微信开放平台,然后用公众号的账号扫描进入,在基本设置里面设置开发者密码和服务器访问的白名单ip,多个ip用回车隔开。

​​​

如本地调试不知道自己本地外网IP的话,可以先不设置,后面debug报错的提示信息里面会有你的ip

如果需要绑定小程序的话,可以点击左侧的小程序管理,没有操作过的话,右边会显示开通。

我自己点击开通点了五六次,等了十分钟才显示出来,不知道是微信的问题还是本地的网络问题。

开通之后,会有添加,填入自己的小程序AppID,即可关联

2.代码操作

package com.ruoyi.common.core.domain.entity.miniprogram;import java.util.List;public class OfficialAccountVo {private Integer pageIndex;private Integer pageSize;private Integer totalPage;private List<OfficialAccount> objectList;public Integer getPageIndex() {return pageIndex;}public void setPageIndex(Integer pageIndex) {this.pageIndex = pageIndex;}public Integer getPageSize() {return pageSize;}public void setPageSize(Integer pageSize) {this.pageSize = pageSize;}public Integer getTotalPage() {return totalPage;}public void setTotalPage(Integer totalPage) {this.totalPage = totalPage;}public List<OfficialAccount> getObjectList() {return objectList;}public void setObjectList(List<OfficialAccount> objectList) {this.objectList = objectList;}
}
package com.ruoyi.common.core.domain.entity.miniprogram;public class OfficialAccount {private String  title;private String url;private String thumbUrl;private String thumbMedialId;private String isDelete;private String author;private String digest;private String content;private String onlyFansCanComment;private String showOverPic;private String contentSourceUrl;private String needOpenComment;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public String getThumbUrl() {return thumbUrl;}public void setThumbUrl(String thumbUrl) {this.thumbUrl = thumbUrl;}public String getThumbMedialId() {return thumbMedialId;}public void setThumbMedialId(String thumbMedialId) {this.thumbMedialId = thumbMedialId;}public String getIsDelete() {return isDelete;}public void setIsDelete(String isDelete) {this.isDelete = isDelete;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public String getDigest() {return digest;}public void setDigest(String digest) {this.digest = digest;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getOnlyFansCanComment() {return onlyFansCanComment;}public void setOnlyFansCanComment(String onlyFansCanComment) {this.onlyFansCanComment = onlyFansCanComment;}public String getShowOverPic() {return showOverPic;}public void setShowOverPic(String showOverPic) {this.showOverPic = showOverPic;}public String getContentSourceUrl() {return contentSourceUrl;}public void setContentSourceUrl(String contentSourceUrl) {this.contentSourceUrl = contentSourceUrl;}public String getNeedOpenComment() {return needOpenComment;}public void setNeedOpenComment(String needOpenComment) {this.needOpenComment = needOpenComment;}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.miniprogram.OfficialAccount;
import com.ruoyi.common.core.domain.entity.miniprogram.OfficialAccountVo;
import org.springframework.web.bind.annotation.*;import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.*;@RestController
@RequestMapping("/miniApp/officialAccount")
public class OfficialAccountController {/*** 获取公众号发布文章列表* @param officialAccountVo* @return* @throws IOException*/@ResponseBody@PostMapping(value = "/getContentList")private AjaxResult getContentList(@RequestBody OfficialAccountVo officialAccountVo) throws IOException {String result1 = getWxAppToken();Map<String, Object> token1 = (Map<String, Object>) JSON.parseObject(result1);
//        String path = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + token1.get("access_token").toString(); --获取素材String path = "https://api.weixin.qq.com/cgi-bin/freepublish/batchget?access_token=" + token1.get("access_token").toString();//模拟http请求URL url = new URL(path);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("POST");connection.setDoOutput(true);connection.setRequestProperty("content-type", "application/json");connection.connect();// post发送的参数Map<String, Object> map = new HashMap<>();map.put("offset", (officialAccountVo.getPageIndex()-1)* officialAccountVo.getPageSize()); //分页内容起始indexmap.put("count", officialAccountVo.getPageSize());  //显示内容数量map.put("no_content", 0);  //1 表示不返回 content 字段,0 表示正常返回,默认为 0// 将map转换成json字符串String paramBody = JSON.toJSONString(map);OutputStream out = connection.getOutputStream();BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));bw.write(paramBody); // 向流中写入参数字符串bw.flush();InputStream in = connection.getInputStream();byte[] b = new byte[100];int len = -1;StringBuffer sb = new StringBuffer();while ((len = in.read(b)) != -1) {sb.append(new String(b, 0, len));}in.close();JSONObject json = JSONObject.parseObject(sb.toString());//以上是已经获取到文章列表,下面是视业务场景进行json操作,如不需要则直接返回sb.toString()。//取出json中的itemString item = json.getString("item");//查看返回的总数String total = json.getString("total_count");officialAccountVo.setTotalPage(Integer.valueOf(total));List<OfficialAccount> arrayList = new ArrayList<>();//如果返回的列表总数为0就没必要解析了if(Integer.valueOf(total)>0) {//item为数组json类型,这时需要转换成JSONArrayJSONArray jsonArray = JSONObject.parseArray(item);int size = jsonArray.size();List<String> contentList = new ArrayList<>();for (int i = 0; i < size; i++) {JSONObject jsonObject = jsonArray.getJSONObject(i);String content = jsonObject.getString("content");contentList.add(content);}//解析文章内容contentList.forEach(data -> {//content为文章模块JSONObject jsonObject = JSON.parseObject(data);//取出文章列表信息并转成jsonString news = jsonObject.getString("news_item");JSONArray jsonArray1 = JSONObject.parseArray(news);//循环数组jsonfor (int i = 0; i < jsonArray1.size(); i++) {JSONObject jsonObject1 = jsonArray1.getJSONObject(i);OfficialAccount jsonEntity = new OfficialAccount();jsonEntity.setThumbUrl(jsonObject1.getString("thumb_url"));jsonEntity.setThumbMedialId(jsonObject1.getString("thumb_media_id"));jsonEntity.setIsDelete(jsonObject1.getString("is_deleted"));jsonEntity.setAuthor(jsonObject1.getString("author"));jsonEntity.setOnlyFansCanComment(jsonObject1.getString("only_fans_can_comment"));jsonEntity.setDigest(jsonObject1.getString("digest"));jsonEntity.setShowOverPic(jsonObject1.getString("show_cover_pic"));jsonEntity.setContentSourceUrl(jsonObject1.getString("content_source_url"));jsonEntity.setNeedOpenComment(jsonObject1.getString("need_open_comment"));jsonEntity.setTitle(jsonObject1.getString("title"));jsonEntity.setContent(jsonObject1.getString("content"));jsonEntity.setUrl(jsonObject1.getString("url"));arrayList.add(jsonEntity);}});}officialAccountVo.setObjectList(arrayList);return AjaxResult.success(officialAccountVo);}/*** 获取公众号token* @return* @throws MalformedURLException* @throws IOException* @throws ProtocolException*/private String getWxAppToken() throws MalformedURLException, IOException, ProtocolException {String path = " https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";String appid = "*******"; //公众号的开发者ID(AppID)String secret = "*******"; //公众号的开发者密码(AppSecret)URL url = new URL(path + "&appid=" + appid + "&secret=" + secret);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.connect();InputStream in = connection.getInputStream();byte[] b = new byte[100];int len = -1;StringBuffer sb = new StringBuffer();while ((len = in.read(b)) != -1) {sb.append(new String(b, 0, len));}in.close();return sb.toString();}
}

上面最后一段代码里面需要讲自己公众号的AppIDAppSecret替换进去;

不知道自己本地外网ip的话,可以在这里打个断点,会提示你的ip信息不在白名单访问名单里面,然后去公众号平台里面添加一下就可以本地测试了

本地测试结果:


总结

代码也比较简单,参考开发文档直接写就好了,有不对的地方还希望各位多多指教。

JAVA 获取微信公众号发布的文章列表内容相关推荐

  1. java对接微信公众号发布文章

    前言 在工作中遇到一个需求,需要向微信公众号发布文章,通过查询资料以及查阅微信的开发文档,最终实现. 微信开发文档:https://developers.weixin.qq.com/doc/offia ...

  2. 手写抓取单个微信公众号的全部文章列表

    单个微信公众号抓取 最近看了很多公众号的文章,突然想把全部的公众号抓取的想法. 于是,搜了一下,发现很多的博客写怎么抓取,但是尝试下来,还是比较麻烦,基本上没有几个可以使用的. 于是研究一下思路,主要 ...

  3. 获取微信公众号未群发文章的永久URL链接

    1.打开公众号里的自定义菜单--点击菜单内容: 2. 跳转网页--从公众号图文消息中选择: 3.选择素材库,确定返回得到永久URL链接: 得到的是长链接,需要短连接,需要在微信里打开后复制链接就可以了 ...

  4. java 获取微信公众号code为空

    失败的原因是没将回调方法encode转换 /** * URL编码(utf-8) * * @param source * @return */ public static String urlEncod ...

  5. 雨听|获取微信公众号推送文章封面图片

    方法 1.在浏览器搜索框中输入相应文章链接 2.鼠标右键-选择"显示网页源代码" 3.ctrl+f 或 command+f ,输入:var msg_cdn_url,按下enter键 ...

  6. java获取微信公众号二维码

    引入依赖: <dependency><groupId>com.github.binarywang</groupId><artifactId>weixin ...

  7. 爬取微信公众号发布的所有文章(包括阅读数,在看数,点赞数)

    这次写爬虫.我爬取了某个微信公众号的全部文章的 文章链接 url 文章标题 title 发布时间 update_time 封面链接 cover 阅读数 read_num 在看数 like_num 若想 ...

  8. 如何获取微信公众号文章ID?9步教你!

    自媒体时代已经到来,越来越多的人开始关注和学习自媒体运营.而在自媒体运营中,微信公众号是一个非常重要的平台.为了更好地运营微信公众号,掌握文章ID获取方法是必不可少的技能之一.本文将从以下9个方面详细 ...

  9. 自动获取微信公众号微信文章信息(每日自动推送)

    自动获取微信公众号微信文章信息 目录 前言 一.获取文章列表 二.自动化获取微信公众号cookie 1.影刀自动登录微信 2.获取公众号cookie 1.安装mitmproxy 2.配合切换代理脚本, ...

最新文章

  1. 强化学习:如何处理大规模离散动作空间
  2. 对话Nullmax无人车CEO徐雷:造血营收L3,追梦宏图L4
  3. 【SICP练习】101 练习2.77-2.78
  4. UNP学习 高级I/O函数
  5. php redis.dll php5.6,在Windows 64位下为PHP5.6.14安装redis扩展
  6. c语言抓取抖音视频,【FiddlerScript】利用Fiddler中的FiddlerScript自动抓取抖音无水印视频并且自动保存...
  7. Flat Tech html5 前端响应式模板
  8. thymeleaf的url属性
  9. jQuery动画stop()用法
  10. dubbo分布式事务解决方案_阿里架构师谈:高并发+分布式+秒杀+微服务+性能优化...
  11. 三次hermite插值matlab,三次hermite插值
  12. 学习自媒体究竟要投入多少?
  13. 英语----形容词和副词
  14. AlertDialog.Builder setPositiveButton 点击时不关闭dialog
  15. KIBA 和 Davis 数据集下载 以及部分学习笔记
  16. spring cloud gateway filters学习
  17. matlab 警告:警告: 更新 Legend 时出错。Not enough input arguments.
  18. cocos2d 简单消除游戏算法 (一)
  19. 《利用Python进行数据分析: Python for Data Analysis 》学习随笔
  20. 论宏观和微观角度理解二极管和三极管的工作原理

热门文章

  1. 用计算机打出98k的歌,抖音绝地求生98K之歌叫什么名字 98K之歌歌词分享
  2. 音视频Share系列3---视频直播系统LSS的技术优化分析
  3. 计算机为啥系统保护设置不了,Win7 64位电脑无法设置屏保怎么办|电脑设置不了屏保的解决方法...
  4. 微信小程序|Tab标签页
  5. 02_IT Boy,你的年终总结缺张图
  6. 《跨境电商 —— 阿里巴巴速卖通实操全攻略》一一1.2 账户的认证流程
  7. 苹果最新审核条例学习
  8. Linux 启动smb服务器,windows连接smb 服务器
  9. 写csv解决Excel打开乱码问题
  10. 浅析即时通讯开发中移动端实时消息推送技术