You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过URL读取JSON遇301重定向及JSON转换异常求助

解决HTTP 301重定向导致的JSON解析失败问题

问题根源

你遇到的org.json.JSONException是因为请求返回了301重定向的HTML页面,而非预期的JSON数据。URL.openStream()方法不会自动跟随HTTP重定向,所以读取到的是重定向跳转的HTML内容,自然无法解析为JSONObject。

解决方案

1. 使用HttpURLConnection处理重定向

替换原有的readUrl方法,用HttpURLConnection发起请求,它默认会自动跟随301/302重定向,同时能更好地控制请求细节:

private static String readUrl(String urlString) throws IOException {
    HttpURLConnection connection = null;
    BufferedReader reader = null;
    try {
        URL url = new URL(urlString);
        connection = (HttpURLConnection) url.openConnection();
        // 明确设置跟随重定向(默认已开启,可省略)
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("GET");
        // 指定接受JSON格式,帮助服务器返回正确内容
        connection.setRequestProperty("Accept", "application/json");

        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (connection != null) {
            connection.disconnect();
        }
    }
}

2. 改用HTTPS协议访问API

从你提供的示例JSON资源URL来看,API域名已强制使用HTTPS。把请求URL的协议从http改成https,可以直接避免重定向:

String url = "https://webservice.fanart.tv/v3/movies/" + movie.id + "?api_key=" + apikey;

验证效果

修改后,请求会自动处理重定向(若仍存在),或直接通过HTTPS获取到正确的JSON数据,就能正常解析hdmovielogo数组并提取英文logo链接了。

内容的提问来源于stack exchange,提问作者Steve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:16:31