解析知乎热榜

Bertha 。 2023-09-28 22:30 98阅读 0赞

背景

实现一个简单的需求,解析知乎热榜,主要涉及找到热榜接口、json解析、返回值中文乱码处理(Unicode编码)、RestTemplate配置等等。

这只是简单的实现了功能,如果需要实际使用还有很多问题没有解决,比如自动获取的频率应该设置为多少,太频繁了可能导致被别人封禁,频率太低又没有时效性;

如果要应对并发访问,可以将获取来了的数据存到自己的缓存系统中去,比如redis中,自己系统访问的时候优先访问本地缓存,缓存的过期时间就参照上面的分析来设置。

以下是简单实现的步骤:

通过某种方式拿到关键接口

  1. https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50

核心逻辑代码

  1. package com.fast.alibaba.service;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.google.gson.Gson;
  6. import org.springframework.stereotype.Service;
  7. import org.springframework.web.client.RestTemplate;
  8. import javax.annotation.Resource;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. /**
  12. * 解析知乎热榜
  13. */
  14. @Service
  15. public class ZhiHuHotListService {
  16. private final static String ZHI_HU_HOT_LIST_URL = "https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50";
  17. @Resource
  18. RestTemplate restTemplate;
  19. public String getZhiHuHot(){
  20. List<String> list = new ArrayList<>();
  21. String str = restTemplate.getForObject(ZHI_HU_HOT_LIST_URL,String.class);
  22. JSONObject parse = (JSONObject)JSON.parse(str);
  23. JSONArray array = (JSONArray)parse.get("data");
  24. for (Object o : array.stream().toArray()) {
  25. JSONObject jso = (JSONObject)o;
  26. String detail_text = (String)jso.get("detail_text");
  27. detail_text = detail_text.trim().replace("万热度","");// 热度,单位万
  28. JSONObject target = (JSONObject)jso.get("target");
  29. String title = (String)target.get("title");// 标题
  30. String url = (String)target.get("url");// 问题链接
  31. url = url.replace("api","www").replace("questions","question");
  32. list.add(title);
  33. System.out.println(title+"\t"+url+"\t"+detail_text);
  34. }
  35. return new Gson().toJson(list);
  36. }
  37. }

RestTemplate处理一下Unicode编码问题

  1. package com.fast.alibaba.config;
  2. import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.web.client.RestTemplate;
  6. @Configuration
  7. public class ApplicationContextConfig {
  8. @Bean
  9. public RestTemplate getRestTemplate(){
  10. RestTemplate restTemplate = new RestTemplate();
  11. restTemplate.getMessageConverters().clear();
  12. restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());//Unicode编码处理
  13. return restTemplate;
  14. }
  15. }

测试效果

670c52057fdc468a8dafd9371d4854a4.png

发表评论

表情:
评论列表 (有 0 条评论,98人围观)

还没有评论,来说两句吧...

相关阅读

    相关 解析

    背景 实现一个简单的需求,解析知乎热榜,主要涉及找到热榜接口、json解析、返回值中文乱码处理(Unicode编码)、RestTemplate配置等等。 这只是简单的实