zoukankan      html  css  js  c++  java
  • Java 网络编程(三) 创建和使用URL访问网络上的资源

     

      创建和使用URL访问网络上的资源

      URL(Uniform Resource Locator)统一资源定位符的简称,它表示Internet上某一资源的地址。

      通过URL我们可以访问Internet上的各种网络资源,比如最常见的WWW, FTP站点。浏览器通过解析给定的URL可以在网络上查找相应的文件或其他资源。

      在目前使用最为广泛的TCP/IP中对于URL中主机名的解析也是协议的一个标准,即所谓的域名解析服务

      使用URL进行网络编程,不需要对协议本身有太多的了解,功能也比较弱,相对而言是比较简单的。

     

    URL组成

      一个URL包括两个主要部分:

      协议标识符:HTTP, FTP, File等。

      资源名字:主机名,文件名,端口号,引用。

     

    创建URL

      在Java程序中,可以创建表示URL地址的URL对象。

      URL对象表示一个绝对的URL地址,但URL对象可用绝对URL、相对URL和部分URL构建。

      创建URL的代码如下,如果创建失败会抛出异常:

          try
          {
             URL myURL = new URL("http://www.google.com.tw/");
          }
          catch (MalformedURLException e)
          {
             //exception handler code here
          }

      

    获得URL对象的各个属性

      URL类中有各种用于获取属性的方法:

      getProtocol

      getHost

      getPort

      getFile

      getRef

      例子程序如下: 

    获取URL对象属性
    package com.example.network;
    
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class URLTest01
    {
        public static void main(String[] args)
        {
    
            try
            {
                URL myURL = new URL(
                        "http://java.sun.com:80/docs/books/tutorial/index.html#DOWN");
    
                String protocal = myURL.getProtocol();
                String host = myURL.getHost();
                String file = myURL.getFile();
                int port = myURL.getPort();
                String ref = myURL.getRef();
    
                System.out.println(protocal + ", " + host + ", " + file + ", "
                        + port + ", " + ref);
            }
            catch (MalformedURLException e)
            {
                // exception handler code here
            }
    
        }
    
    }

    创建和使用URL访问网上资源

      为获得URL的实际比特或内容信息,用它的openConnection()方法从它创建一个URLConnection对象,与调用URL对象相关,它返回一个URLConnection对象。它可能引发IOException异常。

      URLConnection是访问远程资源属性的一般用途的类。如果你建立了与远程服务器之间的连接,你可以在传输它到本地之前用URLConnection来检查远程对象的属性。这些属性由HTTP协议规范定义并且仅对用HTTP协议的URL对象有意义

      URL和URLConnection类对于希望建立与HTTP服务器的连接来获取信息的简单程序来说是非常好的。

      例子程序UrlConnection01,建立连接,从连接对象获取输入流,然后读入,再写出到文件中去。 

    程序UrlConnection01
    package com.example.network;
    
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    
    public class UrlConnection01
    {
        public static void main(String[] args) throws Exception
        {
            URL url = new URL("http://www.baidu.com/");
    
            // 打开连接
            URLConnection conn = url.openConnection();
    
            // 得到输入流
            InputStream is = conn.getInputStream();
    
            // 关于IO流的用法和写法一定要熟悉
            OutputStream os = new FileOutputStream("d:\\baidu.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对象获取输入流,见例子程序UrlConnection02。

    程序UrlConnection02
    package com.example.network;
    
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    
    public class UrlConnection02
    {
        public static void main(String[] args) throws Exception
        {
            URL url = new URL("http://www.baidu.com/");
    
            // // 打开连接
            // URLConnection conn = url.openConnection();
            //
            // // 得到输入流
            // InputStream is = conn.getInputStream();
    
            // 另一种得到输入流的方法:通过url直接获取
            InputStream is = url.openStream();
    
            // 关于IO流的用法和写法一定要熟悉
            OutputStream os = new FileOutputStream("d:\\baidu.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();
    
        }
    
    }

       查看源代码可以看到内部实现机制是一样的: 

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

       程序代码UrlConnection03用字符流的方式读取网站内容显示在控制台上。  

    程序UrlConnection03
    package com.example.network;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URL;
    
    public class UrlConnection03
    {
    
        public static void main(String[] args) throws Exception
        {
            URL url = new URL("http://www.google.com.tw/");
    
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    url.openStream()));
    
            String line = null;
    
            while (null != (line = br.readLine()))
            {
                System.out.println(line);
    
            }
    
            br.close();
        }
    }

     

    参考资料

      圣思园张龙老师Java SE系列视频教程。

  • 相关阅读:
    妙用||和&&
    jQuery细节总结
    Mybatis3.2和Spring3.x整合----Myb…
    SSH整合- 2- add service layout
    SSH整合--1
    MyBatis之ResultMap简介,关联对象…
    BeanFactory和ApplicationContext介绍
    Spring IOC容器
    感知机算法的两种表示
    Python中xPath技术和BeautifulSoup的使用
  • 原文地址:https://www.cnblogs.com/mengdd/p/2951877.html
Copyright © 2011-2022 走看看