代码:
public class Demo3 {
public static void main(String[] args)throws IOException {
getResponse();
}
//向服务器一个网页发送请求并得到该网页返回的内容
public static void getResponse() throws IOException{
String path = "http://top.baidu.com/?fr=super_card";
URL url = new URL(path);
//打开与服务器的连接,得到链接的对象(还不是建立链接,只是打开那道门)
//URLConnection urlcon = url.openConnection();
//建立链接 为什么不建立链接也可?
//urlcon.connect();
//得到此链接中的输入流对象(不通过URLConnection直接获取输入流对象)
BufferedReader br = new BufferedReader(new
InputStreamReader(url.openStream()));
//将网页上得到的数据存入本地文件
PrintWriter pw = new PrintWriter(new
FileOutputStream("file\\baidu.html"));
String line = null;
while((line=br.readLine())!=null){
pw.println(line);
}
}
}
//为什么上面可以直接获取到服务器端的响应,因为在调用url.openStream()时,其实内部已经实现了打开链接(url.openConnection()方法,以及getInputStream()方法)
查看源代码:openStream()方法源代码:
public final InputStream
openStream() throws java.io.IOException {
return
openConnection().getInputStream();//实现了打开链接,并直接返回该输入流对象,所以实现了对openStream()方法的封装。
}