views:

1191

answers:

5

I wanted to know if there is any standard APIs in Java to validate a given URL? I want to check both if the URL string is right i.e. the given protocol is valid and then to check if a connection can be established.

I tried using HttpURLConnection, providing the URL and connecting to it. The first part of my requirement seems to be fulfilled but when I try to perform HttpURLConnection.connect(), 'java.net.ConnectException: Connection refused' exception is thrown.

Can this be because of proxy settings? I tried setting the System properties for proxy but no success.

Let me know what I am doing wrong.

+2  A: 

http://java.sun.com/j2se/1.4.2/docs/api/java/net/URL.html

If the constructor throws an exception => URL invalid

Martin Hohenberg
Thanks, I was in need of such solution, didnt want to open a connection to the site to validate the URL syntax.
mizipzor
A: 

I think this question is very similar: http://stackoverflow.com/questions/285860/how-can-i-programmatically-test-an-http-connection

Sinuhe
+2  A: 

Are you sure you're using the correct proxy as system properties?

Also if you are using 1.5 or 1.6 you could pass a java.net.Proxy instance to the openConnection() method. This is more elegant imo:

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);
NickDK
+3  A: 

You need to create both a URL object and a URLConnection object. The following code will test both the format of the URL and whether a connection can be established:

try {
    URL url = new URL("http://www.yoursite.com/");
    URLConnection conn = url.openConnection();
    conn.connect();
} catch (MalformedURLException e) {
    // the URL is not in a valid form
} catch (IOException e) {
    // the connection couldn't be established
}
Olly
A: 

Hey,

Thanks. Opening the URL connection by passing the Proxy as suggested by NickDK works fine.

//Proxy instance, proxy ip = 10.0.0.1 with port 8080 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080)); conn = new URL(urlString).openConnection(proxy);

System properties however doesn't work as I had mentioned earlier.

Thanks again.

Regards, Keya

Keya
Hi Keya. If NickDK's answer is the correct one, you should accept it and then add a comment, rather than "replying" by answering your own question. You can read more in the FAQ at http://meta.stackoverflow.com/questions/5234/accepting-answers-what-is-it-all-about
Matt Solnit
My apologies and thanks for the pointer.
Keya