2015-03-03 87 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()); 

现在你会得到出头