Is Java's URI.resolve incompatible with RFC 3986 when the relative URI contains an empty path?

后端 未结 3 1758
生来不讨喜
生来不讨喜 2021-01-04 07:09

I believe the definition and implementation of Java\'s URI.resolve method is incompatible with RFC 3986 section 5.2.2. I understand that the Java API defines how that method

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-04 07:49

    If you want better1 behavior from URI.resolve() and do not want to include another large dependency2 in your program, then I found the following code to work well within my requirements:

    public URI resolve(URI base, URI relative) {
        if (Strings.isNullOrEmpty(base.getPath()))
            base = new URI(base.getScheme(), base.getAuthority(), "/",
                base.getQuery(), base.getFragment());
        if (Strings.isNullOrEmpty(uri.getPath()))
            uri = new URI(uri.getScheme(), uri.getAuthority(), base.getPath(),
                uri.getQuery(), uri.getFragment());
        return base.resolve(uri);
    }
    

    The only non-JDK thing there is Strings from Guava, for readability - replace with your own 1-line-method if you don't have Guava.

    Footnotes:

    1. I cannot claim that the simple code sample here is RFC3986 compliant.
    2. Such as Spring, javax.ws or - as mentioned in this answer - Apache HTTPClient.

提交回复
热议问题