java URL类详细讲解及使用实例分析

时间:2018-11-07
本文章向大家介绍java URL类详细讲解及使用实例分析,需要的朋友可以参考一下

一、URL

  URL类表示统一资源定位符,指向万维网上“资源”的指针。

  资源可以是简单的文件或目录,也可以是对更复杂对象的引用,比如对数据库或搜索引擎的查询。

  URL即是定位也是资源,定位到网络中一个具体的资源。

  URL主要由四部分组成:

  1、协议(例如http) 2、资源主机域名(例如www.baidu.com) 

  3、端口号(例如80端口)  4、资源文件(网站中具体资源文件,例如index.html)

  1.1构造方法

  URL(String protocol, String host, int port, String file)

  //协议,资源域名,端口号,资源文件
  URL(String spec);//绝对地址构建URL
  URL(URL context, String spec);//相对地址构造URL,相对context而言。

  1.2主要方法

  int getPort()//获取端口
  String getProtocol()//获取协议
  String getHost()//获取主机名 | 域名
  String getFile()//获取资源信息
  String getRef()//获取锚点
  String getQuery()//获取参数
  String getPath()//获取相对路径,相对资源主机域名而言。

  

  1.3例子

import java.net.MalformedURLException;
import java.net.URL;

public class url {

    public static void main(String[] args) throws MalformedURLException {
        // TODO Auto-generated method stub
        /*协议:http          
         *资源主机域名:www.baidu.com   
         *端口: 80
         *资源文件:index.html       
         *锚点 :aa
         *参数:uname=hcf
         * */
        URL b = new URL("http://www.baidu.com:80/index.html#aa?uname=hcf");
        URL b1 = new URL("http://www.baidu.com:80/index.html?uname=hcf");
        System.out.println("b协议:" + b.getProtocol());//获取http协议
        System.out.println("b主机名:"+b.getHost());//获取资源主机域名www.baidu.com
        System.out.println("b端口号:" + b.getPort());
        System.out.println("b资源文件" + b.getFile());
        System.out.println("b相对地址:" + b.getPath());
        System.out.println("b锚点:" + b.getRef());//b中锚点和参数一起出现会导致冲突,会将#后面都认为是锚点
        System.out.println("b参数:" + b.getQuery());//导致参数为null
        System.out.println("b1锚点:" + b1.getRef());
        System.out.println("b1参数:" + b1.getQuery());//去掉锚点后的b1的参数就可以正常获取
    }
}
运行结果:
b协议:http
b主机名:www.baidu.com
b端口号:80
b资源文件/index.html
b相对地址:/index.html
b锚点:aa?uname=hcf
b参数:null
b1锚点:null
b1参数:uname=hcf

  1.4 URL中的流

  InputStream openStream()//返回此URL链接的输入流

  前面说了URL是资源也是定位,可以把网络看做是一个电脑,

  把URL看做是这个电脑中具体的文件路径。

  然后通过这个URL构造一个输入流。

  

  下面举一个小例子:

  读取baidu首页资源(即网页源代码)然后写入html文件中,打开htimport java.import java.iimportimport java.io.FileOutputimport java.io.IOException;

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;

public class url {
    public static void main(String[] args) throws IOException {
        String  temp;
        URL b = new URL("http://www.baidu.com:80/index.html");
     //输出流进行写操作后文件存放位置,要指定编码方法不然出现乱码
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("F:\依风\Desktop\baidu.html")),"UTF-8"));
        BufferedReader br = new BufferedReader(new InputStreamReader(b.openStream(),"UTF-8"));
        while(null != (temp = br.readLine())){//每次读取一行,然后将内容写入baidu.html文件
             bw.write(temp);
             System.out.println(temp);
        }
        bw.flush();
        bw.close();
        br.close();
    }
}
运行结果:
<!DOCTYPE html>                            //网页源代码中指定了编码方式为UTF-8
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

打开baidu.html会显示出平常我们看到的百度首页,

有些图片是存放在www.baidu.com的服务器上的,引用这些图片一般是相对路径(相对于百度服务器)引用,

我们这里的html是本地文件所以引用图片时路径会存在一些问题,所以有些图片无法正常显示。

但首页的大概的框架我们是可以看到的,这里只是一个本地的静态的网页,所以点击百度一下是没用的。。。

点击有些功能可能有用。