java 网络编程回顾(一)

来源:互联网 发布:php员工信息管理系统 编辑:程序博客网 时间:2024/04/29 03:14

URL回顾:

import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.net.URL;import java.net.URLConnection;public class URITest {public static void main(String[] args)  throws Exception{URL url = new URL("http://www.hao123.com");URLConnection connection = url.openConnection();InputStream is = connection.getInputStream();OutputStream os = new FileOutputStream("C:/hao123.txt");byte[] buffer = new byte[2048];int length = 0;while(-1 != (length = is.read(buffer, 0, buffer.length))){os.write(buffer, 0, length);}is.close();os.close();}}

另一种方式是通过url的openstream方法直接获得输入流而无需获取connection,内部调用过程是一样的,只不过这种方式少些一行代码:

import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.net.URL;public class URLTest2 {public static void main(String[] args)  throws Exception{URL url = new URL("http://www.hao123.com");//URLConnection connection = url.openConnection();//InputStream is = connection.getInputStream();OutputStream os = new FileOutputStream("C:/hao1234.html");InputStream is = url.openStream();byte[] buffer = new byte[2048];int length = 0;while(-1 != (length = is.read(buffer, 0, buffer.length))){os.write(buffer, 0, length);}is.close();os.close();}}

查看opensream方法可以看到

 public final InputStream openStream() throws java.io.IOException {return openConnection().getInputStream();    }

   public URLConnection openConnection() throws java.io.IOException {return handler.openConnection(this);    }

abstract protected URLConnection openConnection(URL u) throws IOException;
最终都是通过connection获得。





0 0
原创粉丝点击