huanghongfa
2021-07-21 acf716af1f13ba2f910c883c58f6e07be6a0ce79
小程序获取公众号文章接口
1个文件已添加
128 ■■■■■ 已修改文件
springcloud_k8s_panzhihuazhihuishequ/applets/src/main/java/com/panzhihua/applets/api/WxOfficialApi.java 128 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
springcloud_k8s_panzhihuazhihuishequ/applets/src/main/java/com/panzhihua/applets/api/WxOfficialApi.java
New file
@@ -0,0 +1,128 @@
package com.panzhihua.applets.api;
import com.alibaba.fastjson.JSON;
import com.panzhihua.common.model.vos.R;
import com.panzhihua.common.utlis.StringUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/official")
public class WxOfficialApi {
    //公众号appid
    private List<String> appidList = new ArrayList<String>(){{this.add("wx7c733ebbf6c55ecf");this.add("wxc94f0cddf13577d5");}};
    //公众号secret
    private List<String> secretList = new ArrayList<String>(){{this.add("500290552cbfdd1c1c18131c5807b6ae");this.add("3418127405845701497a09f65678953f");}};
    /**
     * 获取token
     * @param appid     公众号appid
     * @param secret    公众号secret
     * @return  token
     */
    private String getToken(String appid,String secret) 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";
        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));
        }
//        System.out.println(sb.toString());
        in.close();
        return sb.toString();
    }
    /**
     * 通过token获取公众号文章
     * @param token token
     * @return  获取的文章列表结果
     */
    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,0,len));
        }
        in.close();
        return sb.toString();
    }
    @ApiOperation(value = "拉取公众号列表")
    @GetMapping("/list/noToken")
    public R pageDiscuss() throws Exception{
        WxOfficialApi officialApi = new WxOfficialApi();
        List<String> tokenList = new ArrayList<>();
        if(!appidList.isEmpty()){
            for (int i = 0; i < appidList.size(); i++) {
                String token = officialApi.getToken(appidList.get(i),secretList.get(i));
                log.info("通过appid:"+appidList.get(i)+"获取token返回参数:" + token);
                if(StringUtils.isNotEmpty(token)){
                    tokenList.add(token);
                }
            }
        }
        List<String> resultList = new ArrayList<>();
        if(!tokenList.isEmpty()){
            tokenList.forEach(token -> {
                try {
                    String result = officialApi.getContentList(token);
                    log.info("通过token获取文章列表成功,返回结果:" + result);
                    resultList.add(result);
                }catch (Exception e){
                    log.error("通过token获取文章列表失败,错误原因:" + e.getMessage());
                }
            });
        }
        return R.ok(resultList);
    }
}