Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URISyntaxException Illegal character in query

Tags:

java

uri

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.

like image 692
Harshit Gupta Avatar asked Sep 02 '13 13:09

Harshit Gupta


3 Answers

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=!"
like image 55
Evgeniy Dorofeev Avatar answered Oct 22 '22 22:10

Evgeniy Dorofeev


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();
    }
}
like image 37
Satish Pawar Avatar answered Oct 22 '22 21:10

Satish Pawar


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;
like image 12
Sotirios Delimanolis Avatar answered Oct 22 '22 22:10

Sotirios Delimanolis