views:

49

answers:

1

Hello there, this problem is bugging me:

HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
con.setRequestMethod("HEAD");
 if (con.getResponseCode()!=200 ){dosomething()}

Is this the correct way to set the Request Method, or is it already too late since I called URL.openConnection() and it already made the connection using the default which is GET?

I can't call setRequestMethod("HEAD") in the same line as openConnection because it returns a URLConnection,not a HttpURLConnection.

So how do I ensure that the method will always be HEAD knowing the default is GET?

Should I just use HttpClient ?

+2  A: 

That's the correct method.

Calling openConnection() doesn't actually do anything. The request isn't "committed" (that is, nothing is sent to the server) until you ask for something that is returned in the server's response, like the body of the response (con.getInputStream()), the status (con.getResponseCode()), or some other response header. This gives you time to set options on the HttpUrlConnection, like whether you plan to send a request body (i.e., POST), set the request method, etc.

By the way, you could set the method "on the same line," but being on the same line is meaningless: either openConnection() sends the request method, or it doesn't. Method calls that happen after are not a factor, regardless of the line they are on.

erickson
Drat! This means I have to look elsewhere for my bottleneck! Thank you for the answer.
Voulnet