微信小程序获取公众号文章列表及显示文章的示例代码
微信小程序中如何打开公众号中的文章,步骤相对来说不麻烦。
1、公众号设置
小程序若要获取公众号的素材,公众号需要做一些设置。
1.1绑定小程序
公众号需要绑定目标小程序,否则无法打开公众号的文章。
在公众号管理界面,点击小程序管理-->关联小程序
1.2公众号开发者功能配置
(1)在公众号管理界面,点击开发模块中的基本配置选项。
(2)开启开发者秘密(AppSecret),注意保存改秘密。
(3)设置ip白名单,这个就是发起请求的机器的外网ip,假如是在自己电脑那就是自己电脑的外网ip,若部署到服务器那就是服务器的外网ip。
2、获取文章信息的步骤
以下只是作为演示。
实际项目中在自己的服务端程序中获取,不要在小程序中直接获取,毕竟要使用到appid、appsecret这些保密性高的参数。
2.1获取access_token
access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。API文档
privateStringgetToken()throwsMalformedURLException,IOException,ProtocolException{
//access_token接口https请求方式:GEThttps://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
Stringpath="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
Stringappid="公众号的开发者ID(AppID)";
Stringsecret="公众号的开发者密码(AppSecret)";
URLurl=newURL(path+"&appid="+appid+"&secret="+secret);
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStreamin=connection.getInputStream();
byte[]b=newbyte[100];
intlen=-1;
StringBuffersb=newStringBuffer();
while((len=in.read(b))!=-1){
sb.append(newString(b,0,len));
}
System.out.println(sb.toString());
in.close();
returnsb.toString();
}
2.2获取文章列表
API文档
privateStringgetContentList(Stringtoken)throwsIOException{
Stringpath="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+token;
URLurl=newURL(path);
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("content-type","application/json;charset=utf-8");
connection.connect();
//post发送的参数
Mapmap=newHashMap<>();
map.put("type","news");//news表示图文类型的素材,具体看API文档
map.put("offset",0);
map.put("count",1);
//将map转换成json字符串
StringparamBody=JSON.toJSONString(map);//这里用了Alibaba的fastjson
OutputStreamout=connection.getOutputStream();
BufferedWriterbw=newBufferedWriter(newOutputStreamWriter(out));
bw.write(paramBody);//向流中写入参数字符串
bw.flush();
InputStreamin=connection.getInputStream();
byte[]b=newbyte[100];
intlen=-1;
StringBuffersb=newStringBuffer();
while((len=in.read(b))!=-1){
sb.append(newString(b,0,len));
}
in.close();
returnsb.toString();
}
测试:
@Test
publicvoidtest()throwsIOException{
Stringresult1=getToken();
Maptoken=(Map)JSON.parseObject(result1);
Stringresult2=getContentList(token.get("access_token").toString());
System.out.println(result2);
}
转换成json格式,参数说明查看上面的API文档
其中第二张图片中的url即为公众号文章的地址,获取到多少片tem项中就会有多少项,只要得到上面的结果那么在小程序中打开公众号文章已经成功一大半了。
最后在小程序中利用
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。