Skip to main content
gamedev.net
🔒 Locked

Java net code question. Specifically URL class.

Started by Hauk 3 replies 650+ views
Original Post
Hauk
Hauk
Hi guys/gals, Just a quick question for you. I was just wondering can i use the 'getRef()' method in the Java URL class to check if a URL exists or not? It would look something like this:

//Create a new URL object
URL myURL = new URL(myAddress);

//Check if the URL exists.
myURL.getRef();

System.out.println("The URL exists.");
Thats just a very basic implementation, but I just want you to see what I'm talking about. Thanks for the help guys :) Hauk
Fukushuusha
Fukushuusha
The getRef() method returns the anchor of the URL or if there is none it returns null.That would mean that the URL as an object could exist but the anchor could just be null.So it depends on how you want to use it on the program I guess.
Hauk
Hauk
Hmm, would there be a more solid way of checking if the URL is valid. It's just after browsing through the Java Net API, there isn't a specific function to verify a URL.

Cheers,

Hauk
Fukushuusha
Fukushuusha
Hmmm I am not sure about what I will say now since I have not tried it.

You could use openConnection() method of the URL class.This will return to an httpUrlConnection object if the URL is http.Then you could use the method

getResponseCode() of the httpUrlConnectionObject.To sum it all up just do a check on the returned int of the method.If it is :

200 --> URL is ok
401 --> URL is unauthorized
-1 --> response is not valid HTTP

So in other words the int returned by this method returns the HTTP status or -1.

Hope I helped
Hauk
Hauk
Cool man, thanks for the help. I'll see if I can implement that tomorrow morning. Right now, the mind cries for sleep :)

Again, thanks

Hauk

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.