• Java 网络编程:(八)URL网络编程


    一、URL 概述

      1、URL(Uniform Resource Locator):统一资源定位符,它表示 Internet 某一资源的地址。

      2、它是一种具体的URI,即URL可以用来标识一个资源,而且还指明了如何 locate 这个资源。

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

      4、URL的基本结构由5部分组成:

    <传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
    

        例如:

    http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123

        #片段名:即锚点,例如看小说,直接定位到章节;

        参数列表格式:参数名=参数值&参数名=参数值...

      5、URL 应用

      

    二、URL 类构造器

      为了表示URLjava.net 中实现了类 URL。我们可以通过下面的构造器来初始化一个 URL 对象:

    public URL (String spec):通过一个表示URL地址的字符串可以构造一个URL对象。
    例如: URL url = new URL ("http://www.google.com/");
    
    public URL(URL context, String spec):通过基 URL 和相对 URL 构造一个 URL 对象。
    例如: URL downloadUrl = new URL(url, “download.html")
    
    public URL(String protocol, String host, String file);
     例如: new URL("http","www.google.com", “download. html");
    
    public URL(String protocol, String host, int port, String file); 
    例如: URL gamelan = new URL("http", "www.google.com", 80, “download.html");
    

      

       URL类的构造器都声明抛出非运行时异常,必须要对这一异常进行处理,通常是用 try-catch 语句进行捕获。

    三、URL 常用方法

      一个URL对象生成后,其属性是不能被改变的,但可以通过它给定的方法来获取这些属性:

    public String getProtocol( ) 获取该URL的协议名
    public String getHost( ) 获取该URL的主机名
    public String getPort( ) 获取该URL的端口号
    public String getPath( ) 获取该URL的文件路径
    public String getFile( ) 获取该URL的文件名
    public String getQuery( ) 获取该URL的查询名
    

      

      Demo:

     1   public static void main(String[] args) {
     2 
     3         try {
     4 
     5             URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");
     6 
     7 //            public String getProtocol(  )     获取该URL的协议名
     8             System.out.println(url.getProtocol());
     9 //            public String getHost(  )           获取该URL的主机名
    10             System.out.println(url.getHost());
    11 //            public String getPort(  )            获取该URL的端口号
    12             System.out.println(url.getPort());
    13 //            public String getPath(  )           获取该URL的文件路径
    14             System.out.println(url.getPath());
    15 //            public String getFile(  )             获取该URL的文件名
    16             System.out.println(url.getFile());
    17 //            public String getQuery(   )        获取该URL的查询名
    18             System.out.println(url.getQuery());
    19 
    20 
    21         } catch (MalformedURLException e) {
    22             e.printStackTrace();
    23         }
    24 
    25     }

    四、针对 HTTP 协议的 URLConnection 类

      URL的方法 openStream():能从网络上读取数据
      若希望输出数据,例如向服务器端的 CGI (公共网关接口-Common Gateway Interface-的简称,是用户浏览器和服务器端的应用程序进行连接的接口)程序发送一些数据,

      则必须先与URL建立连接,然后才能对其进行读写,此时需要使用URLConnection


      URLConnection:表示到URL所引用的远程对象的连接。当与一个URL建立连接时,首先要在一个 URL 对象上通过方法 openConnection() 生成对应的 URLConnection对象。

      如果连接过程失败,将产生IOException。

    URL netchinaren = new URL ("http://www.google.com/index.shtml");
    URLConnectonn u = netchinaren.openConnection( );
    

      

      通过URLConnection对象获取的输入流和输出流,即可以与现有的CGI程序进行交互。

    public Object getContent( ) throws IOException
    
    public int getContentLength( )
    
    public String getContentType( )
    
    public long getDate( )
    
    public long getLastModified( )
    
    public InputStream getInputStream( )throws IOException
    
    public OutputSteram getOutputStream( )throws IOException
    

      

    五、案例

      使用URL下载图片并保存到本地

     1   public static void main(String[] args) {
     2 
     3         HttpURLConnection urlConnection = null;
     4         InputStream is = null;
     5         FileOutputStream fos = null;
     6         try {
     7             URL url = new URL("http://localhost:8080/examples/beauty.jpg");
     8             //1.生成 url 连接对象
     9             urlConnection = (HttpURLConnection) url.openConnection();
    10        //2. 连接到指定的 URL 上面
    11             urlConnection.connect();
    12 
    13             is = urlConnection.getInputStream();
    14             fos = new FileOutputStream("beauty2.jpg");
    15 
    16             byte[] buffer = new byte[1024];
    17             int len;
    18             while((len = is.read(buffer)) != -1){
    19                 fos.write(buffer,0,len);
    20             }
    21 
    22             System.out.println("下载完成");
    23         } catch (IOException e) {
    24             e.printStackTrace();
    25         } finally {
    26             //关闭资源
    27             if(is != null){
    28                 try {
    29                     is.close();
    30                 } catch (IOException e) {
    31                     e.printStackTrace();
    32                 }
    33             }
    34             if(fos != null){
    35                 try {
    36                     fos.close();
    37                 } catch (IOException e) {
    38                     e.printStackTrace();
    39                 }
    40             }
    41             if(urlConnection != null){
    42                 urlConnection.disconnect();
    43             }
    44         }
    45 
    46     }

    六、URI、URL和URN的区别

      URI,是 uniform resource identifier,统一资源标识符用来唯一的标识一个资源。

      而URLuniform resource locator,统一资源定位符,它是一种具体URI,即URL可以用来标识一个资源,而且还指明了如何locate这个资源。

      而URNuniform resource name,统一资源命名,是通过名字来标识资源,比如mailto:java-net@java.sun.com

      也就是说, URI是以一种抽象的,高层次概念定义统一资源标识,而URLURN则是具体的资源标识的方式。 URLURN都是一种URI

      在JavaURI中,一个URI实例可以代表绝对的,也可以是相对的,只要它符URI的语法规则。而URL类则不仅符合语义,还包含了定位该资源的信息,因此它不能是相对的。

      

  • 相关阅读:
    matplotlib数据可视化之柱形图
    xpath排坑记
    Leetcode 100. 相同的树
    Leetcode 173. 二叉搜索树迭代器
    Leetcode 199. 二叉树的右视图
    Leetcode 102. 二叉树的层次遍历
    Leetcode 96. 不同的二叉搜索树
    Leetcode 700. 二叉搜索树中的搜索
    Leetcode 2. Add Two Numbers
    Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
  • 原文地址:https://www.cnblogs.com/niujifei/p/14879849.html
Copyright © 2020-2023  润新知