我正在尝试从API网址获取JSON,但我正在获取java.io.IOException: Server returned HTTP response code: 403
。
如果我只是将链接放在浏览器中,它就可以正常工作。这是链接(用访问令牌替换TOKEN):API
我认为代码在工作,因为当我使用JSONPlaceHolder链接时https://jsonplaceholder.typicode.com/todos/
我的代码:
private static String streamToString(InputStream inputStream) {
String text = new Scanner(inputStream, "UTF-8").useDelimiter("\\Z").next();
return text;
}
public static String jsonGetRequest(String urlQueryString) {
String json = null;
try {
URL url = new URL(urlQueryString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
InputStream inStream = connection.getInputStream();
json = streamToString(inStream); // input stream to string
} catch (IOException ex) {
ex.printStackTrace();
}
return json;
}
答案 0 :(得分:1)
该站点正在阻止默认的Java用户代理。您需要通过setRequestProperty
设置另一个:
connection.setRequestProperty("User-Agent","useragent");
请注意,代理的实际身份并不重要,只要它不是默认代理即可。
使用“ a”的用户代理: