为什么当我尝试打开 URL 时会收到 403 错误 [英] Why do I get a 403 error when I try open a URL
本文介绍了为什么当我尝试打开 URL 时会收到 403 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在使用来自 http://imdbapi.org 的 imdb api 来获取有关电影的一些信息.当我使用 API 并尝试在 Java 中打开这个 url 时,它给了我 403 错误.该 url 应该以 JSON 格式返回数据.到目前为止,这是我的代码(Java 7):
I am currently using the imdb api from http://imdbapi.org to get some information about a movie. When I use the API and try to open this url in java it gives me a 403 error. The url is supposed to return the data in JSON. Here is my code so far(Java 7):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class Test {
public static void main(String[] args) {
URL url =null;
try {
url = new URL("http://imdbapi.org/?q=batman");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream is =null;
try {
is = url.openConnection().getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = new BufferedReader( new InputStreamReader( is ) );
String line = null;
try {
while( ( line = reader.readLine() ) != null ) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(line);
}
}
推荐答案
你应该设置User-Agent
:
System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
或
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
is = connection.getInputStream();
这篇关于为什么当我尝试打开 URL 时会收到 403 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文