【问题标题】:Http response code 429 while reading HTML读取 HTML 时的 Http 响应代码 429
【发布时间】:2018-09-28 08:19:00
【问题描述】:

在 java 中,我想从 URL(instagram)读取并保存所有 HTML,但得到错误 429(请求过多)。我认为这是因为我试图阅读比请求限制更多的行。

StringBuilder contentBuilder = new StringBuilder();
try {
    URL url = new URL("https://www.instagram.com/username");
    URLConnection con = url.openConnection();
    InputStream is =con.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(is));
    String str;
    while ((str = in.readLine()) != null) {
        contentBuilder.append(str);
    }
    in.close();
} catch (IOException e) {
    log.warn("Could not connect", e);
}
String html = contentBuilder.toString();

错误就是这样;

Could not connect
java.io.IOException: Server returned HTTP response code: 429 for URL: https://www.instagram.com/username/

而且它还表明由于这一行而发生错误

InputStream is =con.getInputStream();

有人知道我为什么会收到此错误和/或如何解决它吗?

【问题讨论】:

标签: java instagram http-status-codes rate-limiting http-status-code-429


【解决方案1】:

问题可能是由于连接未关闭/断开造成的。 对于用于自动关闭的输入 try-with-resources,即使在异常或返回时也很有用。您还构建了一个 InputStreamReader,它将使用运行应用程序的机器的默认编码,但您需要 URL 内容的字符集。 readLine 返回没有行尾的行(这通常非常有用)。所以加一个。

StringBuilder contentBuilder = new StringBuilder();
try {
    URL url = new URL("https://www.instagram.com/username");
    URLConnection con = url.openConnection();
    try (BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream(), "UTF-8"))) {
        String line;
        while ((line = in.readLine()) != null) {
            contentBuilder.append(line).append("\r\n");
        }
    } finally {
        con.disconnect();
    } // Closes in.
} catch (IOException e) {
    log.warn("Could not connect", e);
}
String html = contentBuilder.toString();

【讨论】:

  • 嗨,感谢您的回复,但我不明白 URLConnection 应该在哪里
  • 然后我在 URLConnection 中得到一个不兼容的类型错误。必需:java.lang.AutoCloseable 找到:java.net.URLConnection
  • 我这边的愚蠢错误; SQLConnection 是可自动关闭的。 URLConnection 使用disconnect()。更正了代码。
  • 请求过多可能源于连接数。超时需要半小时才能正常关闭连接。 添加日志记录,以确保代码不会多次执行,例如在重绘期间。
  • 我发现了问题。在 html 中只有最后 12 个帖子。这就是为什么我不能以这种方式获得更多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 2014-04-20
  • 2018-05-26
  • 2015-02-01
  • 1970-01-01
  • 2020-11-12
相关资源
最近更新 更多