URLEncoder's solution does not work for me, perhaps because it encodes only everything. I tried to use apache HttpGet and it throws an error with the url as a string encoded this way.
In my case, this strange code was correct:
URL url = new URL(pageURLAsUnescapedString); URI uri = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), url.getRef());
Somehow url.toURI does not work like that. URI constructors work in two ways: if you use one with one String parameter, the constructor pretends that the provided uri is correctly escaped (and therefore an error, the same thing happens with the String HttpGet constructor); if you use a multi-line URI constructor for multiple lines, then the class handles all unrecoverable very well (and HttpGet has a different constructor that accepts a URI). Why does URL.toURI () not do this? I have no clue ...
Hope this helps someone, it took me a few hours to figure this out.
Federico pugnali
source share