I was expecting this code to return a 404, however it produces the output :
“Response code is 200”
Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,
try
{
// create the HttpURLConnection
URL url = new URL("http://www.thisurldoesnotexist");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
System.out.println("Response code is " + connection.getResponseCode());
}
EDIT: I see you’ve call
openConnection()but notconnect()– could that be the problem? I would expectgetResponseCode()to actually make the request if it hasn’t already, but it’s worth just trying that…That suggests you’ve possible got some DNS resolver which redirects to a “helper” (spam) page, or something like that.
The easiest way to see exactly what’s going on here is to use Wireshark – have that up and capturing traffic (HTTP-only, to make life easier) and then run your code. You should be able to see what’s going on that way.
Note that I wouldn’t have expected a 404 – because that would involve being able to find a web server to talk to to start with. If you’re trying to go to a host which doesn’t involve, there shouldn’t be an HTTP response at all. I’d expect
connect()to throw an exception.