从 java 中的 URL 获取页面内容
Get page content from URL in java
无法通过以下代码从 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);
}
}
正如我上面的评论,您需要通过 setRequestProperty 方法设置用户代理 header,如下所示。
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());
现在你会得到东西!!
无法通过以下代码从 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);
}
}
正如我上面的评论,您需要通过 setRequestProperty 方法设置用户代理 header,如下所示。
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());
现在你会得到东西!!