Java获取Url中的参数Map-创新互联

从URL中获取请求参数Map
String url =“http://jd.com?a=1&b=2&c=2&a=2&a=${test}”;
->map

创新互联长期为成百上千客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为山东企业提供专业的成都网站设计、成都网站建设山东网站改版等技术服务。拥有十多年丰富建站经验和众多成功案例,为您定制开发。1、使用UriComponentsBuilder
import org.junit.jupiter.api.Test;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

    @Test
    public void testGetRequestParams(){String url ="http://jd.com?a=1&b=2&c=2&a=2&a=${test}";
        MultiValueMapqueryParams = UriComponentsBuilder.fromHttpUrl(url).build().getQueryParams();
        System.out.println(queryParams);
    }

结果:

{a=[1, 2, ${test}], b=[2], c=[2]}
2、使用hutool工具
import cn.hutool.http.HttpUtil;
import java.nio.charset.StandardCharsets;

    @Test
    public void testHutool(){String url ="http://jd.com?a=1&b=2&c=2&a=2&a=${test}";
        Map>stringListMap = HttpUtil.decodeParams(url, "UTF-8");
        System.out.println("decodeParams:" + stringListMap);
        // 获取单值map最后一个会覆盖上一个
        MapstringStringMap = HttpUtil.decodeParamMap(url, StandardCharsets.UTF_8);
        System.out.println("decodeParamMap:" + stringStringMap);
        // map 转 URL params
        String urlParams = HttpUtil.toParams(stringStringMap);
        System.out.println("urlParams: "+urlParams);

    }

结果:

decodeParams:{a=[1, 2, ${test}], b=[2], c=[2]}
decodeParamMap:{a=${test}, b=2, c=2}
urlParams: a=$%7Btest%7D&b=2&c=2
3、Java 8实现
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;

@Test
    public void testURL() throws MalformedURLException {String url ="http://jd.com?a=1&b=2&c=2&a=2&a=${test}";
        System.out.println(splitQuery(new URL(url)));

    }

    public Map>splitQuery(URL url){if (Strings.isNullOrEmpty(url.getQuery())) {return Collections.emptyMap();
        }
        return Arrays.stream(url.getQuery().split("&"))
                .map(this::splitQueryParameter)
                .collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, mapping(Map.Entry::getValue, toList())));
    }

    public SimpleImmutableEntrysplitQueryParameter(String it)  {final int idx = it.indexOf("=");
        final String key = idx >0 ? it.substring(0, idx) : it;
        final String value = idx >0 && it.length() >idx + 1 ? it.substring(idx + 1) : null;
        try {return new SimpleImmutableEntry<>(
                    URLDecoder.decode(key, StandardCharsets.UTF_8.name()),
                    URLDecoder.decode(value, StandardCharsets.UTF_8.name())
            );
        } catch (UnsupportedEncodingException e) {throw new RuntimeException(e);
        }
    }

结果:

{a=[1, 2, ${test}], b=[2], c=[2]}
4、使用org.apache.http.client.utils.URLEncodedUtils
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;

    @Test
    public void test04() throws UnsupportedEncodingException, URISyntaxException {String url ="http://jd.com?a=1&b=2&c=2&a=2&a=$%7Btest%7D";
        Listparams = URLEncodedUtils.parse(new URI(url).getQuery(), StandardCharsets.UTF_8);
        for (NameValuePair param : params) {System.out.println(param.getName() + " : " + param.getValue());
        }
        System.out.println(params);
    }

结果:

a : 1
b : 2
c : 2
a : 2
a : ${test}
[a=1, b=2, c=2, a=2, a=${test}]
5、java11 实现
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
import java.util.stream.Collectors;

    @Test
    public void test05() throws MalformedURLException {String url ="http://jd.com?a=1&b=2&c=2&a=2&a=$%7Btest%7D";
        List>list = Pattern.compile("&")
                .splitAsStream(new URL(url).getQuery())
                .map(s ->Arrays.copyOf(s.split("=", 2), 2))
                .map(o ->Map.entry(decode(o[0]), decode(o[1])))
                .collect(Collectors.toList());
        System.out.println(list);

        Map>map = Pattern.compile("&")
                .splitAsStream(new URL(url).getQuery())
                .map(s ->Arrays.copyOf(s.split("=", 2), 2))
                .collect(groupingBy(s ->decode(s[0]), mapping(s ->decode(s[1]), toList())));
        System.out.println(map);
    }

    private static String decode(final String encoded) {return Optional.ofNullable(encoded)
                .map(e ->URLDecoder.decode(e, StandardCharsets.UTF_8))
                .orElse(null);
    }

结果:

[a=1, b=2, c=2, a=2, a=${test}]
{a=[1, 2, ${test}], b=[2], c=[2]}

参考:
https://stackoverflow.com/questions/13592236/parse-a-uri-string-into-name-value-collection

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


分享题目:Java获取Url中的参数Map-创新互联
文章源于:http://hbruida.cn/article/cesocd.html