Java获取Reddit指定分类JSON数组异常:返回Hot分类数据
解决Reddit API请求Top分类返回Hot数据的问题
我之前也踩过Reddit API的这个坑,你遇到的情况几乎可以肯定是请求头缺少合法的User-Agent字段导致的——Reddit对没有自定义UA的请求会做特殊处理,要么直接返回默认的Hot分类数据,要么把请求重定向到Hot页面,而浏览器访问时自带了浏览器的UA,所以能正常拿到Top内容。
下面是具体的解决步骤和代码示例:
1. 必须设置合规的User-Agent请求头
Reddit的API明确要求请求必须携带一个有意义的User-Agent,用来标识你的应用。不能使用Java网络库默认的UA(比如Java/1.8.0_291这类),否则会被判定为不规范请求,返回默认内容。
你可以设置类似这样的UA:"MyWallpaperScraper/1.0 (by u/YourRedditUsername)"
(把YourRedditUsername换成你的Reddit用户名,或者自定义的应用标识)
2. 确保请求处理重定向
有些时候Reddit会对不规范请求返回3xx重定向响应,如果你在Java代码中关闭了自动重定向,就会拿到重定向后的Hot页面数据。大部分Java网络库默认是开启自动重定向的,但可以显式确认这一点。
3. 代码示例(HttpURLConnection)
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class RedditTopDataFetcher { public static void main(String[] args) { try { // 目标Top分类的JSON URL URL redditUrl = new URL("https://www.reddit.com/r/wallpapers/top/.json"); HttpURLConnection connection = (HttpURLConnection) redditUrl.openConnection(); // 设置关键的User-Agent头 connection.setRequestProperty("User-Agent", "MyWallpaperApp/1.0 (by u/YourRedditName)"); // 显式开启自动重定向(默认已开启,可省略,但加上更稳妥) connection.setInstanceFollowRedirects(true); // 读取响应内容 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder responseJson = new StringBuilder(); while ((line = reader.readLine()) != null) { responseJson.append(line); } reader.close(); connection.disconnect(); // 输出获取到的Top分类JSON System.out.println(responseJson.toString()); } catch (Exception e) { e.printStackTrace(); } } }
4. 代码示例(OkHttp 3.x)
如果你用OkHttp这类更简洁的网络库,同样要记得设置UA:
import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class RedditOkHttpExample { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://www.reddit.com/r/wallpapers/top/.json") .header("User-Agent", "MyWallpaperApp/1.0 (by u/YourRedditName)") .build(); try (Response response = client.newCall(request).execute()) { System.out.println(response.body().string()); } } }
额外提示
如果需要指定Top分类的时间范围(比如日榜、周榜、年榜),可以在URL后添加t参数,比如:https://www.reddit.com/r/wallpapers/top/.json?t=week
参数值可以是hour、day、week、month、year、all。
内容的提问来源于stack exchange,提问作者Bryan W
相关产品推荐
相关产品推荐

