300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > JAVA 获取微信公众号发布的文章列表内容

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

时间:2018-07-11 19:04:30

相关推荐

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

文章目录

代码业务场景

一、前提操作

二、开始操作

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

2.代码操作

总结

代码业务场景

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

一、介绍

开始翻了下微信公众号的开发文档,其实文档里面些的很清楚,怎么访问,怎么获取,怎么解析写的一清二处,不清楚的同学可以看下链接:微信开放平台公众号开发文档

看了下网上说的一些还要公众号绑定小程序,其实如果只是单纯的获取公众号里面的文章信息的话,是不需要绑定的,如果要在小程序里面打开公众号返回的文章url的话,才需要绑定。

二、开始操作

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

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

​​​

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

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

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

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

2.代码操作

package mon.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 mon.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 mon.core.domain.AjaxResult;import mon.core.domain.entity.miniprogram.OfficialAccount;import mon.core.domain.entity.miniprogram.OfficialAccountVo;import org.springframework.web.bind.annotation.*;import java.io.*;import .HttpURLConnection;import .MalformedURLException;import .ProtocolException;import .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./cgi-bin/material/batchget_material?access_token=" + token1.get("access_token").toString(); --获取素材String path = "https://api./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./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信息不在白名单访问名单里面,然后去公众号平台里面添加一下就可以本地测试了

本地测试结果:

总结

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。