2
String arg="http://www.example.com/user.php?id=<URLRequest Method='GetByUID' />";
java.net.URI uri = new java.net.URI( arg );
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
desktop.browse( uri );

I want to open the given link in default browser with the above code but it says the url is invalid...i tried escaping characters like ' also but its not working. If i replace String arg="www.google.com"; then there is no problem and I am able to open google.com. Please help.

3 Answers 3

6

Your string contains characters that aren't valid in a URI, per RFC 2396. You need to properly encode the query parameters. Many utilities support that, like the standard URLEncoder (lower level), JAX-RS UriBuilder, Spring UriUtils, Apache HttpClient URLEncodedUtils and so on.

Edit: Oh, and the URI class can handle it, too, but you have to use a different constructor:

URI uri = new URI("http", "foo.com", null, "a=<some garbage>&b= |{$0m3 m0r3 garbage}| &c=imokay", null);
System.out.println(uri);

Outputs:

http://foo.com?a=%3Csome%20garbage%3E&b=%20%7C%7B$0m3%20m0r3%20garbage%7D%7C%20&c=imokay

which, while ugly, is the correct representation.

Sign up to request clarification or add additional context in comments.

Comments

2

Thats because it is invalid. <URLRequest Method='GetByUID' /> should be replaced by the value of the id, or an expression that returns the id which you can concatenate with the arg string. Something like

String arg="http://www.example.com/user.php?id="+getByUID(someUid);

4 Comments

no i actually want it that way only example.com/user.php?id=<URLRequest Method='GetByUID' />.........is there any way to do that?
@lbrt Try to escape all the non-text chars.
@lbrt I don't see how that could be; I'd need to see the encoded output to believe that--see Andrew's answer.
@DaveNewton: He probably encoded the whole URI, which would incorrectly replace the :, /, ?, and =.
1
import java.net.URL;
import java.net.URLEncoder;

class ARealURL {
    public static void main(String[] args) throws Exception {
        String s1 = "http://www.example.com/user.php?id=";
        String param = "<URLRequest Method='GetByUID' />";
        String encodedParam = URLEncoder.encode(param,"UTF-8");

        URL url = new URL(s1+encodedParam);
        System.out.println(url);
    }
}

Output

http://www.example.com/user.php?id=%3CURLRequest+Method%3D%27GetByUID%27+%2F%3E

1 Comment

This encodes spaces as +. What if I want spaces encoded as %20 ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.