微信小程序获取关联微信公众号文章列表
首先应在公众号里面点击“小程序管理”,关联上对应的小程序,输入小程序AppID绑定,到此绑定算是完成
接下来就是要得到AppID和AppSecret,这个在小程序管理中即可查看
下一步就是获取access_token,这个案例用的是Java所写
代码如下:
private String getWxAppToken() 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 = "*********"; //公众号的开发者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,0,len));
}
in.close();
return sb.toString();
}
获取到token后,用token为凭证拉取文章列表
/**
*
* @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); //这边是相当于自己查询分页 目前值为0,也可以是1-N,根据文章篇幅定义,这里场景是分页效果
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发送的参数
Map<String, Object> map = new HashMap<>();
map.put("type", "news"); // news表示图文类型的素材,具体看API文档
map.put("offset", Integer.valueOf(offset));
map.put("count", 1); //count为有多少个模块篇幅,这边是一个是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());
//以上是已经获取到文章列表,下面是视业务场景进行json操作,如不需要则直接返回sb.toString()。
//取出json中的item
String item=json.getString("item");
//item为数组json类型,这时需要转换成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为文章模块
JSONObject jsonObject = JSON.parseObject(content);
//取出文章列表信息并转成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);
}
在此也为补强自己的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之间的转换
*/
public static void testComplexJSONStrToJSONObject(){
System.out.println(COMPLEX_JSON_STR);
JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
//JSONObject jsonObject1 = JSONObject.parseObject(COMPLEX_JSON_STR);//因为JSONObject继承了JSON,所以这样也是可以的
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之间的转换
*/
public static void testJSONStrToJSONArray(){
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
//JSONArray jsonArray1 = JSONArray.parseArray(JSON_ARRAY_STR);//因为JSONArray继承了JSON,所以这样也是可以的
//遍历方式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之间的转换
*/
public static void testJSONStrToJSONObject(){
JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
//JSONObject jsonObject1 = JSONObject.parseObject(JSON_OBJ_STR); //因为JSONObject继承了JSON,所以这样也是可以的
System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
}
public static void demoJson() {
/**
* 将 Json 形式的字符串转换为 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 形式的字符串转换为 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());
}
}
如有更好的方式及有可以优化的地方,可以留言讨论学习鸭