URL类协议 主机 端口 文件 路径 参数获取url对象的url连接器对象

package demo.network.other;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

class URL类 {
    public static void main(String[] args) throws IOException {
        URL url = new URL("https://www.baidu.com/s?wd=Java&rsv_spt=1&rsv_iqid=0xbcf41467000415c5&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_sug3=2&rsv_sug2=0&inputT=2681&rsv_sug4=2681");
        System.out.println("协议: " + url.getProtocol());
        System.out.println("主机:" + url.getHost());
        System.out.println("端口:" + url.getPort());
        System.out.println("文件:" + url.getFile());//文件=路径?参数
        System.out.println("路径:" + url.getPath());
        System.out.println("参数:" + url.getQuery());

//        InputStream in = url.openStream();

//获取url对象的url连接器对象。将连接封装成了对象:URLConnection = java中内置的可以解析的具体协议的对象 + socket.
        URLConnection conn = url.openConnection();
        InputStream in = conn.getInputStream();

        System.out.println("网页数据:");
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf)) != -1) {
            System.out.println(new String(buf, 0, len));
        }
        in.close();
    }
}

上一篇:URL与URI


下一篇:2020-3-14学习地图