简体   繁体   English

从Java中的URL获取页面内容

[英]Get page content from URL in java

Not able to access content of this page "kissanime.com" (it's not returning anything) from URL by this code : 无法通过以下代码从URL访问此页面“ kissanime.com”的内容(不返回任何内容):

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

As my above comment , you need to set user agent header by setRequestProperty method as below. 作为我上面的评论,您需要通过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());

Now you will get somethings !! 现在你会得到一些东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM