开发者

What happened to URIUtil.encodePath from commons-httpclient-3.1?

开发者 https://www.devze.com 2022-12-25 23:57 出处:网络
I want to do what\'s described in question 724043, namely encode the path components of a URI. The class recommended to do that is URIUtil from Commons HttpClient 3.1. Unfortunately, that class seems

I want to do what's described in question 724043, namely encode the path components of a URI. The class recommended to do that is URIUtil from Commons HttpClient 3.1. Unfortunately, that class seems to have disappeared from the most recent version of HttpClient. A similarly named class from HttpClient 4.1, URIUtils, doesn't provide the same functionality. Has this class/method been moved to some other library that I'm not aware of or is it just gone? Am I best off just copying the class from the 3.1 release into my code or is开发者_JS百科 there a simpler way?


The maintainers of the module have decreed that you should use the standard JDK URI class instead:

The reason URI and URIUtils got replaced with the standard Java URI was very simple: there was no one willing to maintain those classes.

There is a number of utility methods that help work around various issues with the java.net.URI implementation but otherwise the standard JRE classes should be sufficient, should not they?

So, the easiest is to look at the source of encodePath from the 3.1 release and duplicate what it does in your own code (or just copy the method/class into your codebase).

Or you could go with the accepted answer on the question you referred to (but it seems you have to break the URL into parts first):

new URI(
    "http", 
    "search.barnesandnoble.com", 
    "/booksearch/first book.pdf",
    null).toString();


This can be achieved using org.apache.http.client.utils.URIBuilder utility in httpclient-4.X () as follows.

    public static String encodePath(final String path) {
       if(path.length() == 0)
          return "";
       else
          return new URIBuilder().setPath(path).toString();
    }


You can use Standard JDK functions, e.g.

public static String encodeURLPathComponent(String path) {
    try {
        return new URI(null, null, path, null).toASCIIString();
    } catch (URISyntaxException e) {
        // do some error handling
    }
    return "";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消