微信小程序獲取關聯微信公衆号文章列表 - 新聞資訊 - 雲南小程序開發|雲南軟件開發|雲南網站建設-昆明融晨信息技術有限公司

159-8711-8523

雲南網建設/小程序開發/軟件開發

知識

不(bù)管是(shì)網站,軟件還是(shì)小程序,都要(yào / yāo)直接或間接能爲(wéi / wèi)您産生價值,我們在(zài)追求其視覺表現的(de)同時(shí),更側重于(yú)功能的(de)便捷,營銷的(de)便利,運營的(de)高效,讓網站成爲(wéi / wèi)營銷工具,讓軟件能切實提升企業内部管理水平和(hé / huò)效率。優秀的(de)程序爲(wéi / wèi)後期升級提供便捷的(de)支持!

您當前位置>首頁 » 新聞資訊 » 公衆号相關 >

微信小程序獲取關聯微信公衆号文章列表

發表時(shí)間:2020-11-6

發布人(rén):融晨科技

浏覽次數:184

微信小程序獲取關聯微信公衆号文章列表

首先應在(zài)公衆号裏面點擊“小程序管理”,關聯上(shàng)對應的(de)小程序,輸入小程序AppID綁定,到(dào)此綁定算是(shì)完成

接下來(lái)就(jiù)是(shì)要(yào / yāo)得到(dào)AppID和(hé / huò)AppSecret,這(zhè)個(gè)在(zài)小程序管理中即可查看

下一步就(jiù)是(shì)獲取access_token這(zhè)個(gè)案例用的(de)是(shì)Java所寫

代碼如下:

private String getToken() throws MalformedURLException, IOException, ProtocolException {
       grant_type=client_credential&appid=APPID&secret=APPSECRET
       String path = " https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
        String appid = "*********"; //公衆号的(de)開發者ID(AppID)
        String secret = "********"; //公衆号的(de)開發者密碼(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();
    }

獲取到(dào)token後,用token爲(wéi / wèi)憑證拉取文章列表

/**
     *
     * @param
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/getContentList",method = RequestMethod.GET)
    private String getContentList(String offset) throws IOException {
        String result1 = getWxAppToken();
        String content = null;
        System.out.println("==offset====="+offset);  //這(zhè)邊是(shì)相當于(yú)自己查詢分頁 目前值爲(wéi / wèi)0,也(yě)可以(yǐ)是(shì)1-N,根據文章篇幅定義,這(zhè)裏場景是(shì)分頁效果
        Map<String,Object> token1 = (Map<String, Object>) JSON.parseObject(result1);
        //String result2 = getContentList(token1.get("access_token").toString());
        String path = " https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + token1.get("access_token").toString();
        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發送的(de)參數
        Map<String, Object> map = new HashMap<>();
        map.put("type", "news"); // news表示圖文類型的(de)素材,具體看API文檔
        map.put("offset", Integer.valueOf(offset));
        map.put("count", 1);  //count爲(wéi / wèi)有多少個(gè)模塊篇幅,這(zhè)邊是(shì)一個(gè)是(shì)4篇文章
        // 将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());
        //以(yǐ)上(shàng)是(shì)已經獲取到(dào)文章列表,下面是(shì)視業務場景進行json操作,如不(bù)需要(yào / yāo)則直接返回sb.toString()。
        //取出(chū)json中的(de)item
        String item=json.getString("item");
        //item爲(wéi / wèi)數組json類型,這(zhè)時(shí)需要(yào / yāo)轉換成JSONArray 
        JSONArray jsonArray = JSONObject.parseArray(item);
        int size = jsonArray.size();
        for (int i = 0; i < size; i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            content = jsonObject.getString("content");
        }
        //content爲(wéi / wèi)文章模塊
        JSONObject jsonObject = JSON.parseObject(content);
        //取出(chū)文章列表信息并轉成json
        String news = jsonObject.getString("news_item");
        JSONArray jsonArray1 = JSONObject.parseArray(news);
        List<JsonEntity> arrayList = new ArrayList<JsonEntity>();
        //循環數組json
        for (int i = 0; i < jsonArray1.size(); i++){
            JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
            JsonEntity jsonEntity = new JsonEntity();
            jsonEntity.setTitle(jsonObject1.getString("title"));
            jsonEntity.setThumb_url(jsonObject1.getString("thumb_url"));
            jsonEntity.setUrl(jsonObject1.getString("url"));
            arrayList.add(jsonEntity);
        }
        return JSON.toJSONString(arrayList);
    }

在(zài)此也(yě)爲(wéi / wèi)補強自己的(de)json操作,哈哈哈哈

package com.example.demo.json;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.demo.common.Person;
 
public class JsonLib {
	//json字符串-簡單對象型
	private static final String  JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
	//json字符串-數組類型
	private static final String  JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
	//複雜格式json字符串
	private static final String  COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\",\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";
	@SuppressWarnings("unchecked")
   public static void main(String[] args) {
       //demoJson();
		
		//testJSONStrToJSONObject();//json字符串轉化對象
		//testJSONStrToJSONArray();//json數組轉化json對象
		testComplexJSONStrToJSONObject();//json對象嵌套json對象
   }
	
	/**
     * 複雜json格式字符串與JSONObject之(zhī)間的(de)轉換
     */
    public static void testComplexJSONStrToJSONObject(){
    	System.out.println(COMPLEX_JSON_STR);
        JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
        //JSONObject jsonObject1 = JSONObject.parseObject(COMPLEX_JSON_STR);//因爲(wéi / wèi)JSONObject繼承了(le/liǎo)JSON,所以(yǐ)這(zhè)樣也(yě)是(shì)可以(yǐ)的(de)
        System.out.println(jsonObject);
        String teacherName = jsonObject.getString("teacherName");
        Integer teacherAge = jsonObject.getInteger("teacherAge");
        JSONObject course = jsonObject.getJSONObject("course");
        JSONArray students = jsonObject.getJSONArray("students");
        System.out.println(teacherName+"------"+teacherAge+"===json對象===="+course+"----json數組----"+students);
        JSONArray jsonArray = JSON.parseArray(students.toString());
        System.out.println(jsonArray);
    }
	
	/**
     * json字符串-數組類型與JSONArray之(zhī)間的(de)轉換
     */
    public static void testJSONStrToJSONArray(){
 
        JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
        //JSONArray jsonArray1 = JSONArray.parseArray(JSON_ARRAY_STR);//因爲(wéi / wèi)JSONArray繼承了(le/liǎo)JSON,所以(yǐ)這(zhè)樣也(yě)是(shì)可以(yǐ)的(de)
 
        //遍曆方式1
        int size = jsonArray.size();
        for (int i = 0; i < size; i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
        }
 
        //遍曆方式2
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
        }
    }
	
	/**
     * json字符串-簡單對象型與JSONObject之(zhī)間的(de)轉換
     */
    public static void testJSONStrToJSONObject(){
 
        JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
        //JSONObject jsonObject1 = JSONObject.parseObject(JSON_OBJ_STR); //因爲(wéi / wèi)JSONObject繼承了(le/liǎo)JSON,所以(yǐ)這(zhè)樣也(yě)是(shì)可以(yǐ)的(de)
 
        System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
 
    }
	public static void demoJson() {
		/**
		    * 将 Json 形式的(de)字符串轉換爲(wéi / wèi) Map
		    */
		   String str = "{\"name\":\"Tom\",\"age\":90}";
		   JSONObject jsonObject = JSONObject.parseObject(str);
		   Map<String, String> params = JSONObject.parseObject(jsonObject.toString(), new TypeReference<Map<String, String>>(){});
		   System.out.println(params);
 
		   /**
		    * 将 Json 形式的(de)字符串轉換爲(wéi / wèi) JavaBean
		    */
			 str = "{\"id\":\"A001\",\"name\":\"Jack\"}";
			 jsonObject = JSONObject.parseObject(str);
			 System.out.println(jsonObject);
			 Person person = JSON.parseObject(str, new TypeReference<Person>() {});
			 System.out.println(person.toString());
	}
}

如有更好的(de)方式及有可以(yǐ)優化的(de)地(dì / de)方,可以(yǐ)留言讨論學習鴨

相關案例查看更多