1. URL 类

URL 类的两个重要方法:

  • openStream():打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream。

    URL url = new URL("http://www.baidu.com");
    
    InputStream inStream = url.openStream();
    byte[] buffer = new byte[1024];
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    int len = -1;
    while ((len = inStream.read(buffer)) != -1)
    {
        outStream.write(buffer, 0, len);
    }
  • openConnection(): 返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。

    openConnection()方法就可以getOutputStream()以及 getInputStream()
    可以更灵活的进行 request 和 response。

    InputStream inStream = url.openConnection().getInputStream();
posted on 2017-10-01 23:35  未雨愁眸  阅读(181)  评论(0编辑  收藏  举报