Raj Gupta
Raj Gupta

Reputation: 260

URL formatting in Java

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.

Upvotes: 1

Views: 19147

Answers (3)

Ryan Stewart
Ryan Stewart

Reputation: 128779

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.

Upvotes: 6

Andrew Thompson
Andrew Thompson

Reputation: 168815

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

Upvotes: 1

lobster1234
lobster1234

Reputation: 7779

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);

Upvotes: 2

Related Questions