微信小程式獲取公眾號文章列表及顯示文章的示例程式碼
阿新 • • 發佈:2020-03-12
微信小程式中如何開啟公眾號中的文章,步驟相對來說不麻煩。
1、公眾號設定
小程式若要獲取公眾號的素材,公眾號需要做一些設定。
1.1 繫結小程式
公眾號需要繫結目標小程式,否則無法開啟公眾號的文章。
在公眾號管理介面,點選小程式管理 --> 關聯小程式
輸入小程式的AppID搜尋,繫結即可。
1.2 公眾號開發者功能配置
(1) 在公眾號管理介面,點選開發模組中的基本配置選項。
(2) 開啟開發者祕密(AppSecret),注意儲存改祕密。
(3) 設定ip白名單,這個就是發起請求的機器的外網ip,假如是在自己電腦那就是自己電腦的外網ip,若部署到伺服器那就是伺服器的外網ip。
2、獲取文章資訊的步驟
以下只是作為演示。
實際專案中在自己的服務端程式中獲取,不要在小程式中直接獲取,畢竟要使用到appid、appsecret這些保密性高的引數。
2.1 獲取access_token
access_token是公眾號的全域性唯一介面呼叫憑據,公眾號呼叫各介面時都需使用access_token。API文件
private String getToken() throws MalformedURLException,IOException,ProtocolException { // access_token介面https請求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET 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,len)); } System.out.println(sb.toString()); in.close(); return sb.toString(); }
2.2 獲取文章列表
API文件
private String getContentList(String token) throws IOException { String path = " https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + token; URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("content-type","application/json;charset=utf-8"); connection.connect(); // post傳送的引數 Map<String,Object> map = new HashMap<>(); map.put("type","news"); // news表示圖文型別的素材,具體看API文件 map.put("offset",0); map.put("count",1); // 將map轉換成json字串 String paramBody = JSON.toJSONString(map); // 這裡用了Alibaba的fastjson 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,len)); } in.close(); return sb.toString(); }
測試:
@Test public void test() throws IOException { String result1 = getToken(); Map<String,Object> token = (Map<String,Object>) JSON.parseObject(result1); String result2 = getContentList(token.get("access_token").toString()); System.out.println(result2); }
轉換成json格式,引數說明檢視上面的API文件
其中第二張圖片中的url即為公眾號文章的地址,獲取到多少片tem項中就會有多少項,只要得到上面的結果那麼在小程式中開啟公眾號文章已經成功一大半了。
最後在小程式中利用<web-view src="...."></web-view>
元件開啟即可,src中為文章的url地址。
到此這篇關於微信小程式獲取公眾號文章列表及顯示文章的示例程式碼的文章就介紹到這了,更多相關小程式獲取公眾號文章列表內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!