Java UrlUtil工具类(解析url、获取url指定参数值)

文章目录

  • 一、url工具类
  • 二、示例


一、url工具类

package com.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * url工具类
 */
public class UrlUtil {

    public static class UrlEntity {
        /**
         * 基础url
         */
        public String baseUrl;
        /**
         * url参数
         */
        public Map<String, String> params;
    }

    /**
     * 解析url
     * @param url
     * @return
     */
    public static UrlEntity parse(String url) {
        UrlEntity entity = new UrlEntity();
        if (url == null) {
            return entity;
        }
        url = url.trim();
        if (url.equals("")) {
            return entity;
        }
        String[] urlParts = url.split("\\?");
        entity.baseUrl = urlParts[0];
        //没有参数
        if (urlParts.length == 1) {
            return entity;
        }
        //有参数
        String[] params = urlParts[1].split("&");
        entity.params = new HashMap<>();
        for (String param : params) {
            String[] keyValue = param.split("=");
            if (keyValue.length > 1) {
                entity.params.put(keyValue[0], keyValue[1]);
            }
        }

        return entity;
    }

    /**
     * 获取url指定参数值
     * @param url
     * @param key 参数名
     * @return
     */
    public static String getParamsByKey(String url,String key){
        UrlEntity entity = parse(url);
        return entity.params.get(key);
    }
    
}

二、示例

	@Test
    public void testUrl(){
        String url = "http://www.123.com?id=1&name=小明";
        UrlUtil.UrlEntity entity = UrlUtil.parse(url);
        System.out.println("entity.baseUrl = " + entity.baseUrl);						//entity.baseUrl = http://www.123.com
        System.out.println("entity.params = " + entity.params);							//entity.params = {name=小明, id=1}
        System.out.println("entity.params.get(\"id\") = " + entity.params.get("id"));	//entity.params.get("id") = 1

        System.out.println("获取url指定参数值 = " + UrlUtil.getParamsByKey(url, "name"));	//获取url指定参数值 = 小明
    }

你可能感兴趣的:(Java,java)