如何从java中的URL字符串获取路径参数

时间:2016-11-04 17:16:49

标签: java jersey-2.0

我想创建将URL字符串作为参数并返回的函数 MultivaluedHashMap<String, String>作为输出。我有我的url格式,通过它我可以构建UriTemplate类。

所以基本上我想创建类似于requestContext.getUriInfo().getPathParameters()

的功能

所以我的功能将是

public MultivaluedHashMap<String, String> getPathParamtersFromUrl(string url)
{
}

我不知道怎么做到这一点。 注意:我不想提取查询参数。我想提取路径参数。

2 个答案:

答案 0 :(得分:1)

在仔细查看UriTemplate类后,我能够找到解决方案。

 private MultivaluedMap<String, String> getPathParameters(String uri, String strUrlTemplate) {

        UriTemplate template = new UriTemplate(strUrlTemplate);
        Map<String, String> parameters = new HashMap<>();
        Boolean value = template.match(uri, parameters);
        return new MultivaluedHashMap(parameters);

    } 

答案 1 :(得分:0)

这将为您提供除http方案和域名之外的路径参数列表。

    public static void main(String[] args) {
    String url = "http://stackoverflow.com/questions/40428388/how-to-get-path-paramters-from-url-string-in-java";
    System.out.println("The path parameters of url:" + url);
    List<String> p = getPathParamtersFromUrl(url);
    p.stream().forEach(x -> System.out.println(x));
}

private static List<String> getPathParamtersFromUrl(String url) {
    String[] path = url.split("\\?");
    String[] pathparams = path[0].split("\\//");
    String[] param = pathparams[1].split("\\/");
    List<String> p = Arrays.asList(param);
    return p.stream().filter(x -> !x.contains(".")).collect(Collectors.toList());
}