You should in fact URLEncode
the "invalid" characters. Since the string actually contains the complete URL, it's hard to properly URL-encode it. You don't know which slashes /
should be taken into account and which not. You cannot predict that on a raw String
beforehand. The problem really needs to be solved at a higher level. Where does that String
come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.
At any way, if you can ensure that it are only the spaces in URL's which makes it invalid, then you can also just do a char-by-char replace with +
:
URI uri = new URI(string.replace(' ', '+'));
or a string-by-string replace with %20
:
URI uri = new URI(string.replace(" ", "%20"));
Or if you can ensure that it's only the part after the last slash which needs to be encoded, then you can also just do:
int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + URLEncoder.encode(string.substring(pos), "UTF-8"));