java抓取网页代码
来源:程序员人生 发布时间:2015-05-08 08:28:49 阅读次数:3408次
代码以下
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
private String u;
private String encoding;
public static void main(String[] args) throws Exception {
Main client = new Main("http://www.baidu.com/", "UTF⑻");
client.run();
}
public Main(String u, String encoding) {
this.u = u;
this.encoding = encoding;
}
public void run() throws Exception {
URL url = new URL(u);// 根据链接(字符串格式),生成1个URL对象
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();// 打开URL
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(), encoding));// 得到输入流,即取得了网页的内容
String line; // 读取输入流的数据,并显示
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
注:更多java学习资源尽在java教程网
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠