【问题标题】:Server returned HTTP response code: 429 for URL JAVA Reddit JSON服务器返回 HTTP 响应代码:URL JAVA Reddit JSON 的 429
【发布时间】:2020-11-28 23:04:09
【问题描述】:

我正在尝试获取此处找到的 JSON 文件:https://www.reddit.com/r/arabfunny/top.json?limit=100

我有以下代码:

static void getPost() throws Exception {
    String webPage = "https://www.reddit.com/r/arabfunny/top.json?limit=100";

    URL url = new URL(webPage);
    URLConnection request = url.openConnection();
    request.connect();

    JsonParser jp = new JsonParser();
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
    JsonObject rootobj = root.getAsJsonObject();
}

这段代码在运行时抛出如下错误:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 429 for URL: https://www.reddit.com/r/arabfunny/top.json?limit=100

【问题讨论】:

  • HTTP 状态码 429:用户在给定时间内发送了太多请求(“速率限制”)。
  • 为什么我的代码发送了多个请求?我只希望它下载一次文件。我应该看/改变什么?
  • 你在短时间内测试了你的代码多少次?每个测试计为 100 个请求。
  • 使用 Spring Boot 你可以使用RestTemplate,你可以看到一个快速指南here。这将帮助您非常轻松地通过http方法使用Api rest。
  • 这是第一次,我怎样才能让它只做一个请求?

标签: java json reddit


【解决方案1】:

修复问题设置内容类型UrlConnection

request.setRequestProperty("Content-Type", "application/json; utf-8");

完整代码:

package com.example;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) throws IOException {
        String webPage = "https://www.reddit.com/r/arabfunny/top.json?limit=100";

        URL url = new URL(webPage);
        URLConnection request = url.openConnection();
        request.setRequestProperty("Content-Type", "application/json; utf-8");

        JsonParser jp = new JsonParser();
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
        JsonObject rootobj = root.getAsJsonObject();
        System.out.println(rootobj);
    }
}

【讨论】:

  • 这不起作用,仍然返回服务器返回的 HTTP 响应代码:429 对于 URL:reddit.com/r/arabfunny/top.json?limit=100
  • 重试审查示例,第一次执行有效,但休息问题arabfunny,第二次执行成功。
【解决方案2】:

问题已通过添加解决:

request.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

【讨论】:

    猜你喜欢
    • 2019-02-01
    • 2018-04-24
    • 2016-02-24
    • 2014-08-09
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    相关资源
    最近更新 更多