The java.net.URI class can aid; in the documentation of URL you obtain
Note, the URI class acts make escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use an URI
Try one of the constructors including more than one argument, like:
URI uri = new URI(
"http",
"search.barnesandnoble.com",
"/booksearch/first book.pdf",
null);
URL url = uri.toURL();
//or String request = uri.toString();
(the single-argument constructor of URI doesn't escape illegal characters)
Only illegal characters get left by the above code - it doesn't avoid non-ASCII characters (see faith's comment).
The to ASCII string arrangement can be done to get a String just with US-ASCII characters:
URI URI = new URI(
"http",
"search.barnesandnoble.com",
"/booksearch/é",
null);
String request = uri.toASCIIString();
As an URL with an inquiry like http://www.google.com/ig/api?weather=São Paulo, use the 5-parameter version of the constructor:
URI uri = new URI(
"http",
"www.google.com",
"/ig/api",
"weather=São Paulo",
null);
String request = uri.toASCIIString();