如何用Java调用TheTVDB API获取JSON数据并解决登录405问题
TheTVDB v4登录接口405错误解决方案及完整示例
问题原因
TheTVDB v4的/login接口仅支持POST请求,并且API Key和Subscriber Pin需要放在JSON格式的请求体中传递,而非作为URL参数拼接。你当前使用GET请求,因此返回405(方法不允许)错误。
修正后的登录代码示例
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class TVDBLoginExample { public static void main(String[] args) { String apiKey = "你的API Key"; String subscriberPin = "你的Subscriber Pin"; String loginUrl = "https://api4.thetvdb.com/v4/login"; try { URL url = new URL(loginUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法为POST conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); // 开启请求体写入权限 conn.setDoOutput(true); // 构造JSON请求体 String jsonInputString = String.format("{\"apikey\":\"%s\",\"pin\":\"%s\"}", apiKey, subscriberPin); // 将请求体写入流 try (OutputStream os = conn.getOutputStream()) { byte[] input = jsonInputString.getBytes("utf-8"); os.write(input, 0, input.length); } // 获取响应码 int responseCode = conn.getResponseCode(); System.out.println("响应码: " + responseCode); // 读取响应内容 StringBuilder response = new StringBuilder(); try (BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf-8"))) { String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } } System.out.println("登录响应: " + response); // 可通过JSON解析库(如Jackson、Gson)提取响应中的data.token字段,用于后续请求 } catch (IOException e) { e.printStackTrace(); } } }
拉取数据示例(使用登录获取的token)
登录成功后会返回一个token,后续所有数据请求都需要在请求头携带Authorization: Bearer <你的token>。以下是获取剧集详情的示例:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class TVDBDataFetchExample { public static void main(String[] args) { String token = "登录获取的有效token"; // 示例:获取ID为121361的剧集(《绝命毒师》)详情 String fetchUrl = "https://api4.thetvdb.com/v4/series/121361"; try { URL url = new URL(fetchUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); // 携带授权token conn.setRequestProperty("Authorization", "Bearer " + token); int responseCode = conn.getResponseCode(); System.out.println("响应码: " + responseCode); StringBuilder response = new StringBuilder(); try (BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf-8"))) { String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } } System.out.println("剧集数据: " + response); } catch (IOException e) { e.printStackTrace(); } } }
注意事项
- 建议使用JSON解析库处理响应数据,方便提取token和业务字段
- token有有效期,过期后需重新登录获取
- 确保API Key和Subscriber Pin为有效订阅凭证
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

