2013-05-30 168 views
5

我目前使用http://imdbapi.org的imdb api來獲取有關影片的某些信息。當我使用API​​並嘗試在java中打開這個url時,它給我一個403錯誤。該網址應該以JSON的形式返回數據。 這裏是我到目前爲止的代碼(Java 7中):當我嘗試打開一個URL時,爲什麼會出現403錯誤

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); 
    } 
} 
+1

這確實是奇怪的,因爲這個網址爲我工作。 – fge

回答

13

你應該設置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(); 
+1

是的,就是這樣:從命令行執行類似'curl -v --user-agent「Java/1.6.0_14」http://imdbapi.org/?q = batman'的命令,出現403 Forbidden錯誤, HTML正文是這個網站的所有者(imdbapi.org)根據您的瀏覽器的簽名禁止了您的訪問。 –

相關問題