在浏览器地址栏输入要打开的页面地址,点击连接就可以获得所要的页面,那么浏览器是如何工作的呢,这里我用java模拟了一个浏览器程序把页面内容下载到本地文件中。
代码如下:
代码如下:
package web;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class URLWebTester {
public static void main(String[] args) throws Exception {
//要下载的页面
URL url = new URL("http://www.ouyaya.com/");
//打开连接
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
//创建存储页面的本地文件
File file = new File("e://ouyaya.html");
if(!file.exists()) {
file.createNewFile();
}
//输入到文件的输出流
FileOutputStream fos = new FileOutputStream(file);
//用于读取文件的输入流
InputStream inputStream = urlConnection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
/* String tempString = null;
while((tempString = br.readLine()) != null) {
fos.write(tempString);
fos.write("\r\n");
}*/
//下载页面到本地文件
byte[] buffer = new byte[1024];
int length = -1;
while((length = bis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
//关闭流对象
fos.close();
bis.close();
inputStream.close();
}
}