codecamp

URL绝对路径构建和相对路径构建

URL绝对路径构建和相对路径构建: 解决协议和资源问题。

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


public class Test {
    public static void main(String[] args) throws UnknownHostException, MalformedURLException {
        /**
         * http://www.baidu.com:80/index.html#a?uname=xxx
         * 80为默认端口;#a为锚点;uname=xxx是get请求字段。
         */
        //绝对路径构建
        URL url = new URL("http://www.baidu.com:80/index.html#a?uname=xxx");
        System.out.println("协议:"+url.getProtocol());//输出:http。
        System.out.println("域名:"+url.getHost());//输出:www.baidu.com。
        System.out.println("端口:"+url.getPort());//输出:80。
        System.out.println("资源:"+url.getFile());//当有锚点时输出:/index.html,无锚点时输出/index.html?uname=xxx。
        System.out.println("相对路径:"+url.getPath());//输出:/index.html。
        System.out.println("锚点:"+url.getRef());//当有锚点时输出:a?uname=xxx,无锚点时输出null。
        System.out.println("参数:"+url.getQuery());//当有锚点时输出null,无锚点时输出uname=xxx。

        
        //相对路径构建
        url = new URL("http://www.baidu.com:80/a/");
        url = new URL(url, "b/c.txt");
        System.out.println(url.toString());
    }
}
InetSocketAddress
简单的爬虫案例
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }