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 there a simpler way?
3 Answers
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();

- 257,207
- 101
- 511
- 656
-
Thanks for the link to mailing post. I'll see about breaking up the URL and doing it myself. – Edward Dale Apr 09 '10 at 07:52
-
importing from "java.net.URI"? it didn't work for me. – Daniel Jun 18 '15 at 22:02
-
1How to encode this url to be possible to share and then user be able to open the link and see the page : http://yazd20.com//News/2015/11/استند-آب-كمدي-حسن-ريوندي-در-يزد.html – Ahmad Ebrahimi Nov 02 '15 at 21:19
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();
}

- 8,462
- 4
- 42
- 63
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 "";
}

- 32,350
- 30
- 109
- 146