【问题标题】:Why do I get a 403 error when I try open a URL为什么我尝试打开 URL 时收到 403 错误
【发布时间】:2013-05-25 10:46:07
【问题描述】:

我目前正在使用来自http://imdbapi.org 的 imdb api 来获取有关电影的一些信息。当我使用 API 并尝试在 java 中打开这个 url 时,它给了我一个 403 错误。该 url 应该以 JSON 格式返回数据。 到目前为止,这是我的代码(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);
    }
}

【问题讨论】:

  • 这确实很奇怪,因为这个 URL 对我有用。

标签: java api imdb


【解决方案1】:

你应该设置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();

【讨论】:

  • 是的,就是这样:从命令行执行类似curl -v --user-agent "Java/1.6.0_14" http://imdbapi.org/?q=batman 的操作,然后出现403 Forbidden 错误,HTML 正文为The owner of this website (imdbapi.org) has banned your access based on your browser's signature
  • 第二个对我有用
猜你喜欢
  • 1970-01-01
  • 2016-02-10
  • 2014-10-04
  • 1970-01-01
  • 2020-02-13
  • 2015-01-31
  • 2022-01-26
  • 1970-01-01
  • 2021-09-08
相关资源
最近更新 更多