My Java standalone application gets a URL (which points to a file) from the user and I need to hit it and download it. The problem I am facing is that I am not able to encode the HTTP URL address properly...
Example:
URL: http://search.barnesandnoble.com/booksearch/first book.pdf
java.net.URLEncoder.encode(url.toString(), "ISO-8859-1");
returns me:
http%3A%2F%2Fsearch.barnesandnoble.com%2Fbooksearch%2Ffirst+book.pdf
But, what I want is
http://search.barnesandnoble.com/booksearch/first%20book.pdf
(space replaced by %20)
I guess URLEncoder
is not designed to encode HTTP URLs... The JavaDoc says "Utility class for HTML form encoding"... Is there any other way to do this?
Maybe can try UriUtils in org.springframework.web.util
String url=""http://search.barnesandnoble.com/booksearch/;
This will be constant i guess and only filename changes dyamically so get filename
String filename; // get the file name
String urlEnc=url+fileName.replace(" ","%20");
If anybody doesn't want to add a dependency to their project, these functions may be helpful.
We pass the 'path' part of our URL into here. You probably don't want to pass the full URL in as a parameter (query strings need different escapes, etc).
And tests:
You can also use
GUAVA
and path escaper:UrlEscapers.urlFragmentEscaper().escape(relativePath)
You can use a function like this. Complete and modify it to your need :
Example of use :
The result is : http://www.growup.com/folder/int%C3%A9rieur-%C3%A0_vendre?o=4
Please be warned that most of the answers above are INCORRECT.
The
URLEncoder
class, despite is name, is NOT what needs to be here. It's unfortunate that Sun named this class so annoyingly.URLEncoder
is meant for passing data as parameters, not for encoding the URL itself.In other words,
"http://search.barnesandnoble.com/booksearch/first book.pdf"
is the URL. Parameters would be, for example,"http://search.barnesandnoble.com/booksearch/first book.pdf?parameter1=this¶m2=that"
. The parameters are what you would useURLEncoder
for.The following two examples highlights the differences between the two.
The following produces the wrong parameters, according to the HTTP standard. Note the ampersand (&) and plus (+) are encoded incorrectly.
The following will produce the correct parameters, with the query properly encoded. Note the spaces, ampersands, and plus marks.