测试URI如何在没有参数顺序的情况下等于?

时间:2015-10-26 05:07:15

标签: java uri

考虑一下代码:

URI one = URI.create("http://localhost:8081/contextRoot/main.html?one=1&second=2");
URI second = URI.create("http://localhost:8081/contextRoot/main.html?second=2&one=1");
System.out.println(one.equals(second));

并打印false。有没有办法在没有URI参数的情况下测试URI?

1 个答案:

答案 0 :(得分:0)

不幸的是,等于URI / URL对象的方法并不总是这样,你正在等待什么。这就是为什么要将2个URI与不同的参数顺序进行比较(如果您认为,顺序对您来说并不重要),您应该使用一些实用程序逻辑。例如,如下:

public static void main(String... args) {
    URI one = URI.create("http://localhost:8081/contextRoot/main.html?one=1&second=2");
    URI second = URI.create("http://localhost:8081/contextRoot/main.html?second=2&one=1");
    System.out.println(one.equals(second));
    System.out.println(areEquals(one, second));
}

private static boolean areEquals(URI url1, URI url2) {
    //compare the commons part of URI
    if (!url1.getScheme().equals(url1.getScheme()) ||
            !url1.getAuthority().equals(url2.getAuthority()) ||
            url1.getPort() != url2.getPort() ||
            !url1.getHost().equals(url2.getHost())) {
        return false;
    }

    //extract query parameters
    String params1 = url1.getQuery();
    String params2 = url2.getQuery();

    if ((params1 != null && params2 != null) && (params1.length() == params2.length())) {
        //get sorted list of parameters
        List<String> list1 = extractParameters(params1);
        List<String> list2 = extractParameters(params2);

        //since list are sorted and contain String objects, 
        //we can compare the lists objects
        return list1.equals(list2);
    } else {
        return false;
    }
}

//return sorted list of parameters with the values
private static List<String> extractParameters(String paramsString) {
    List<String> parameters = new ArrayList<>();

    String[] paramAr = paramsString.split("&");
    for (String parameter : paramAr) {
        parameters.add(parameter);
    }
    Collections.sort(parameters);
    return parameters;
}