解析URL的主域名和引數 - 工具類
阿新 • • 發佈:2022-04-02
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