I am trying to open a link in default browser. I have used the following code.
String myUrl = "http://www.example.com/engine/myProcessor.jsp?Type=A Type&Name=1100110&Char=!";
try {
Desktop.getDesktop().browse(new URI(myUrl));
} catch (IOException err) {
setTxtOutput("Error: "+err.getMessage());
} catch (URISyntaxException err) {
setTxtOutput("Error: "+err.getMessage());
} catch (Exception err) {
setTxtOutput("Error: "+err.getMessage());
}
I am getting URISyntaxException Illegal character in query at index
I think this is because of characters such as ?, & and ! in my URL. I tried using:
URLEncoder.encode(myUrl, "UTF-8");
But this gives me another error.
Failed to open http%3A%2F%2Fwww.example.com%2F...........
The system cannot find the file specified.
Please can you tell me how to correct the URISyntaxException Illegal character error.
It's because of the whitespace here ...jsp?Type=A Type&...
, you can replace it with +
http://www.example.com/engine/myProcessor.jsp?Type=A+Type&Name=1100110&Char=!"
You can use following code snippet
public static String encode(String queryParameter) {
try {
String encodedQueryParameter = URLEncoder.encode(queryParameter, "UTF-8");
return encodedQueryParameter;
} catch (UnsupportedEncodingException e) {
return "Issue while encoding" + e.getMessage();
}
}
You should not encode the whole URL because the URI class requires a valid protocol. Encode only the parameters
String params = URLEncoder.encode("Type=A Type&Name=1100110&Char=!", "UTF-8");
myUrl = "http://www.example.com/engine/myProcessor.jsp?" + params;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With