简体   繁体   中英

How to get path paramters from URL string in java

I want to create function which will take URL string as a parameter and return MultivaluedHashMap<String, String> as a output. I have format of url with me through which I can construct UriTemplate class.

So basically I want to create functionality similar to requestContext.getUriInfo().getPathParameters()

So my function will be

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

I am not sure how to get this. Note : I don't want to extract query parameters. I want to extract path parameters.

I was able to figure out solution after closely looking at the UriTemplate class.

 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);

    } 

This will give you the path parameter list other than the http scheme and the domain name.

    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 = getPathParametersFromUrl(url);
    p.stream().forEach(x -> System.out.println(x));
}

private static List<String> getPathParametersFromUrl(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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM