解析URL的主域名和参数 - 工具类

package com.xie.test;

import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description 解析URL的主域名和参数工具类
 * @Date 2022-02-24 10:51
 * @Author xie
 */
public class UrlDomainUtils {

    public static String getDomainHost(String url) {

        String pattern = "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)";

        Pattern p = Pattern.compile(pattern);
        String line = url;
        Matcher m = p.matcher(line);

        if(m.find()){
            //匹配结果
            String domain = m.group();
            String message = "解析的URL主域名是------------>%s    原始url is %s";
            System.out.println(String.format(message, domain, url));

            domain = domain.replace("https","http");   //todo 这个替换,根据业务需要来定
            message = "修改解析出的URL主域名的协议成http------------>%s    原始url is %s";
            System.out.println(String.format(message, domain, url));

            domain = domain.replace("http://","");
            message = "修改解析出的URL主域名后去掉协议------------>%s    原始url is %s";
            System.out.println(String.format(message, domain, url));

            return domain;
        }
        System.out.println("未找到的URL主域名");
        return null;
    }

    public static void main(String[] args) {
        String imagUrl = "http://39.12.12.12:8344/test/getvideo?file_id=";
        getDomainHost(imagUrl);

        URI uri = URI.create(imagUrl);
        System.out.println("getPath() = " + uri.getPath());
        System.out.println("getScheme() = " + uri.getScheme());
        System.out.println("getHost() = " + uri.getHost());
        System.out.println("getAuthority() = " + uri.getAuthority());
        System.out.println("getRawAuthority() = " + uri.getRawAuthority());
        System.out.println("getFragment() = " + uri.getFragment());
    }

}

输出:

getPath() = /test/getvideo
getScheme() = http
getHost() = 39.12.12.12
getAuthority() = 39.12.12.12:8344
getRawAuthority() = 39.12.12.12:8344
getFragment() = null
posted @ 2022-04-02 16:46  xiexie0812  阅读(333)  评论(0编辑  收藏  举报