创建和使用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

  例子程序如下:

 1 package com.example.network;
 2 
 3 import java.net.MalformedURLException;
 4 import java.net.URL;
 5 
 6 public class URLTest01
 7 {
 8     public static void main(String[] args)
 9     {
10 
11         try
12         {
13             URL myURL = new URL(
14                     "http://java.sun.com:80/docs/books/tutorial/index.html#DOWN");
15 
16             String protocal = myURL.getProtocol();
17             String host = myURL.getHost();
18             String file = myURL.getFile();
19             int port = myURL.getPort();
20             String ref = myURL.getRef();
21 
22             System.out.println(protocal + ", " + host + ", " + file + ", "
23                     + port + ", " + ref);
24         }
25         catch (MalformedURLException e)
26         {
27             // exception handler code here
28         }
29 
30     }
31 
32 }
View Code

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

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

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

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

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

 1 package com.example.network;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 import java.net.MalformedURLException;
 7 import java.net.URL;
 8 import java.net.URLConnection;
 9 
10 public class UrlConnection01
11 {
12     public static void main(String[] args) throws Exception
13     {
14         URL url = new URL("http://www.baidu.com/");
15 
16         // 打开连接
17         URLConnection conn = url.openConnection();
18 
19         // 得到输入流
20         InputStream is = conn.getInputStream();
21 
22         // 关于IO流的用法和写法一定要熟悉
23         OutputStream os = new FileOutputStream("d:\baidu.txt");
24 
25         byte[] buffer = new byte[2048];
26         int length = 0;
27 
28         while (-1 != (length = is.read(buffer, 0, buffer.length)))
29         {
30             os.write(buffer, 0, length);
31         }
32         is.close();
33         os.close();
34 
35     }
36 
37 }
View Code
 1 package com.example.network;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 import java.net.MalformedURLException;
 7 import java.net.URL;
 8 import java.net.URLConnection;
 9 
10 public class UrlConnection01
11 {
12     public static void main(String[] args) throws Exception
13     {
14         URL url = new URL("http://www.baidu.com/");
15 
16         // 打开连接
17         URLConnection conn = url.openConnection();
18 
19         // 得到输入流
20         InputStream is = conn.getInputStream();
21 
22         // 关于IO流的用法和写法一定要熟悉
23         OutputStream os = new FileOutputStream("d:\baidu.txt");
24 
25         byte[] buffer = new byte[2048];
26         int length = 0;
27 
28         while (-1 != (length = is.read(buffer, 0, buffer.length)))
29         {
30             os.write(buffer, 0, length);
31         }
32         is.close();
33         os.close();
34 
35     }
36 
37 }
View Code

也可以直接从URL对象获取输入流,见例子程序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用字符流的方式读取网站内容显示在控制台上。 

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();
    }
}
原文地址:https://www.cnblogs.com/liu-Gray/p/4793836.html