其他分享
首页 > 其他分享> > J2SE - 提取 Url 上的参数

J2SE - 提取 Url 上的参数

作者:互联网

import com.google.common.base.Splitter;

import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UrlParamsUtils {

    /**
     * 方式一:基于 JDK 的类;支持重复参数
     * @param url
     * @return
     * @throws IOException
     */
    public static Map<String, List<String>> getParamsByNative (String url) throws IOException {

        Map<String, List<String>> params = new HashMap<>();

        int subIdx = url.indexOf("?");
        if (subIdx < 0) return params;

        String query = url.substring(subIdx + 1);
        if(query.trim().length() == 0) return params;

        String[] kvLinkStrArr = query.split("&");

        for (String kvLinkStr : kvLinkStrArr) {

            String[] kvPairArr = kvLinkStr.split("=");

            String key = URLDecoder.decode(kvPairArr[0], "UTF-8");
            String value =  kvPairArr.length == 1 ? "" : URLDecoder.decode(kvPairArr[1], "UTF-8");

            List<String> values = params.get(key);
            if (values == null) {
                values = new ArrayList<>();
                params.put(key, values);
            }
            values.add(value);
        }

        return params;
    }

    /**
     * 方式二:引用 spring-web 包的类;支持重复参数
     */
    public static MultiValueMap<String, String> getParamsBySpring (String url) {

        MultiValueMap<String, String> params = UriComponentsBuilder.fromHttpUrl(url).build().getQueryParams();

        List<String> pv = params.get("type");

        return params;
    }

    /**
     * 方式三:引用 guava 包的类;不支持重复参数
     */
    public static Map<String, String> getParamsByGuava (String url) {

        int subIdx = url.indexOf("?");
        if (subIdx < 0) return null;

        String query = url.substring(subIdx + 1);
        if(query.trim().length() == 0) return null;

        if(query.indexOf("=") < 0) return null;

        Map<String, String> params = Splitter.on("&").withKeyValueSeparator("=").split(query);

        System.out.println(params);

        return params;

    }

}

标签:J2SE,提取,String,Url,url,params,import,return,query
来源: https://blog.csdn.net/u013379717/article/details/109306830