文章目錄
-
代碼業(yè)務場景
一、前提操作
二、開始操作
1.獲取公眾號的開發(fā)者id(AppID)和開發(fā)者密碼(AppSecret),以及設置IP白名單
2.代碼操作
總結(jié)
代碼業(yè)務場景
最近在給客戶開發(fā)一款小程序,然后客戶還有自己運營的公眾號,想要把公眾號里面發(fā)布的一些內(nèi)容能夠同步到小程序里面進行展示。如下所示,獲取公眾號里面的發(fā)表記錄→發(fā)布→發(fā)表成功的文章內(nèi)容,刪除的內(nèi)容是獲取不到的。
一、介紹
開始翻了下微信公眾號的開發(fā)文檔,其實文檔里面些的很清楚,怎么訪問,怎么獲取,怎么解析寫的一清二處,不清楚的同學可以看下鏈接:微信開放平臺公眾號開發(fā)文檔
看了下網(wǎng)上說的一些還要公眾號綁定小程序,其實如果只是單純的獲取公眾號里面的文章信息的話,是不需要綁定的,如果要在小程序里面打開公眾號返回的文章url的話,才需要綁定。
二、開始操作
1.獲取公眾號的開發(fā)者id(AppID)和開發(fā)者密碼(AppSecret),以及設置IP白名單
登錄微信開放平臺,然后用公眾號的賬號掃描進入,在基本設置里面設置開發(fā)者密碼和服務器訪問的白名單ip,多個ip用回車隔開。
????
?如本地調(diào)試不知道自己本地外網(wǎng)IP的話,可以先不設置,后面debug報錯的提示信息里面會有你的ip
如果需要綁定小程序的話,可以點擊左側(cè)的小程序管理,沒有操作過的話,右邊會顯示開通。
我自己點擊開通點了五六次,等了十分鐘才顯示出來,不知道是微信的問題還是本地的網(wǎng)絡問題。
開通之后,會有添加,填入自己的小程序AppID,即可關聯(lián)
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 {
/**
* 獲取公眾號發(fā)布文章列表
* @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發(fā)送的參數(shù)
Map<String, Object> map = new HashMap<>();
map.put("offset", (officialAccountVo.getPageIndex()-1)* officialAccountVo.getPageSize()); //分頁內(nèi)容起始index
map.put("count", officialAccountVo.getPageSize()); //顯示內(nèi)容數(shù)量
map.put("no_content", 0); //1 表示不返回 content 字段,0 表示正常返回,默認為 0
// 將map轉(zhuǎn)換成json字符串
String paramBody = JSON.toJSONString(map);
OutputStream out = connection.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write(paramBody); // 向流中寫入?yún)?shù)字符串
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());
//以上是已經(jīng)獲取到文章列表,下面是視業(yè)務場景進行json操作,如不需要則直接返回sb.toString()。
//取出json中的item
String item = json.getString("item");
//查看返回的總數(shù)
String total = json.getString("total_count");
officialAccountVo.setTotalPage(Integer.valueOf(total));
List<OfficialAccount> arrayList = new ArrayList<>();
//如果返回的列表總數(shù)為0就沒必要解析了
if(Integer.valueOf(total)>0) {
//item為數(shù)組json類型,這時需要轉(zhuǎn)換成JSONArray
JSONArray 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);
}
//解析文章內(nèi)容
contentList.forEach(data -> {
//content為文章模塊
JSONObject jsonObject = JSON.parseObject(data);
//取出文章列表信息并轉(zhuǎn)成json
String news = jsonObject.getString("news_item");
JSONArray jsonArray1 = JSONObject.parseArray(news);
//循環(huán)數(shù)組json
for (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 = "*******"; //公眾號的開發(fā)者ID(AppID)
String secret = "*******"; //公眾號的開發(fā)者密碼(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();
}
}
上面最后一段代碼里面需要講自己公眾號的AppID和AppSecret替換進去;
不知道自己本地外網(wǎng)ip的話,可以在這里打個斷點,會提示你的ip信息不在白名單訪問名單里面,然后去公眾號平臺里面添加一下就可以本地測試了
?本地測試結(jié)果:
文章來源:http://www.zghlxwxcb.cn/news/detail-490442.html
總結(jié)
? 代碼也比較簡單,參考開發(fā)文檔直接寫就好了,有不對的地方還希望各位多多指教。文章來源地址http://www.zghlxwxcb.cn/news/detail-490442.html
到了這里,關于JAVA 獲取微信公眾號發(fā)布的文章列表內(nèi)容的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!