首页 > 解决方案 > 获取 301 状态但数据存在

问题描述

我正在尝试从此链接获取数据: https ://api.spiget.org/v2/authors/1001/

您可以看到它包含一些 JSON 数据。但是当我尝试阅读它时,我得到了这个:

<html>
<head><title>301 Moved Permanently</title><script src="/cdn-cgi/apps/head/FuNWa0bpYJxeKtykPLzC2_Mj2DQ.js"></script></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.4.6 (Ubuntu)</center>
</body>
</html>

我的代码是这样的:

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class WebReader {
    private String url;

    public WebReader(String url) {
        this.url = url;
    }

    public List<String> readLines() {
        List<String> result = new ArrayList<>();

        try {
            URLConnection con = new URL(url).openConnection();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = buffer.readLine()) != null)
                result.add(line);

        } catch (IOException ignored) {}

        return result;
    }

    public String read() {
        List<String> lines = readLines();
        StringBuilder result = new StringBuilder();
        for (String line: lines) {
            result.append(line.replace("\n", "")).append("\n");
        }

        return result.toString();
    }

    public JSONObject readJSON() {
        String data = read();
        System.out.println(url);     // To check the link
        System.out.println(data);    // To check data
        return new JSONObject(data);
    }

}

这适用于 661860 等其他 ID,但一旦我达到 1001,它就会引发异常。

编辑 - - - - - - - - - - - - - - - - - - - - - - - - - ---------------

现在它甚至不适用于其他 ID

标签: javahttphttpurlconnection

解决方案


推荐阅读