2015-03-03 123 views
0

無法通過該代碼URL訪問此頁「kissanime.com」(它不返回任何東西)的內容:獲取頁面內容在Java

String a="http://kissanime.com"; 
    url = new URL(a); 

    URLConnection conn = url.openConnection(); 

try (// open the stream and put it into BufferedReader 
     BufferedReader br = new BufferedReader(
     new InputStreamReader(conn.getInputStream()))) { 
    String inputLine; 
    while ((inputLine = br.readLine()) != null) { 
     System.out.println(inputLine); 
    } 
} 
+1

什麼是你得到的錯誤?你有沒有收到任何數據?請將此添加到您的問題。 – mjuarez 2015-03-03 05:05:06

+0

它不返回任何東西 – 2015-03-03 05:07:15

+0

產生java.io.IOException:服務器返回的HTTP響應代碼:403網址:http://kissanime.com – Cataclysm 2015-03-03 05:11:02

回答

1

正如我上面的評論,您需要通過如下調用setRequestProperty方法設定的用戶代理報頭。

String a = "http://kissanime.com"; 
    URLConnection connection = new URL(a).openConnection(); 
    connection 
      .setRequestProperty("User-Agent", 
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); 
    connection.connect(); 

    BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream(), 
      Charset.forName("UTF-8"))); 

    StringBuilder sb = new StringBuilder(); 
    String line; 
    while ((line = r.readLine()) != null) { 
     sb.append(line); 
    } 
    System.out.println(sb.toString()); 

現在你會得到出頭