/ / ¿Cómo comprobar si existe una URL o devuelve 404 con Java? - java, url, http-status-code-404

¿Cómo comprobar si existe una URL o devuelve 404 con Java? - java, url, http-status-code-404

String urlString = "http://www.nbc.com/Heroes/novels/downloads/Heroes_novel_001.pdf";
URL url = new URL(urlString);
if(/* Url does not return 404 */) {
System.out.println("exists");
} else {
System.out.println("does not exists");
}
urlString = "http://www.nbc.com/Heroes/novels/downloads/Heroes_novel_190.pdf";
url = new URL(urlString);
if(/* Url does not return 404 */) {
System.out.println("exists");
} else {
System.out.println("does not exists");
}

Esto debería imprimir

exists
does not exists

PRUEBA

public static String URL = "http://www.nbc.com/Heroes/novels/downloads/";

public static int getResponseCode(String urlString) throws MalformedURLException, IOException {
URL u = new URL(urlString);
HttpURLConnection huc =  (HttpURLConnection)  u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
return huc.getResponseCode();
}

System.out.println(getResponseCode(URL + "Heroes_novel_001.pdf"));
System.out.println(getResponseCode(URL + "Heroes_novel_190.pdf"));
System.out.println(getResponseCode("http://www.example.com"));
System.out.println(getResponseCode("http://www.example.com/junk"));

Salida

200
200
200
404

Agregue la siguiente línea antes de .connect () y la salida sería 200, 404, 200, 404

huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");

Respuestas

53 para la respuesta № 1

Es posible que desee agregar

HttpURLConnection.setFollowRedirects(false);
// note : or
//        huc.setInstanceFollowRedirects(false)

Si no quieres seguir la redirección (3XX)

En lugar de hacer un "GET", todo lo que necesitas es un "HEAD".

huc.setRequestMethod("HEAD");
return (huc.getResponseCode() == HttpURLConnection.HTTP_OK);

37 para la respuesta № 2

esto funcionó para mí:

URL u = new URL ( "http://www.example.com/");
HttpURLConnection huc =  ( HttpURLConnection )  u.openConnection ();
huc.setRequestMethod ("GET");  //OR  huc.setRequestMethod ("HEAD");
huc.connect () ;
int code = huc.getResponseCode() ;
System.out.println(code);

Gracias por las sugerencias anteriores.


23 para la respuesta № 3

Utilizar HttpUrlConnection llamando openConnection() en su objeto URL.

getResponseCode () le dará la respuesta HTTP una vez que haya leído la conexión.

p.ej.

   URL u = new URL("http://www.example.com/");
HttpURLConnection huc = (HttpURLConnection)u.openConnection();
huc.setRequestMethod("GET");
huc.connect() ;
OutputStream os = huc.getOutputStream();
int code = huc.getResponseCode();

(no probado)


12 para la respuesta № 4

No hay nada malo con su código. Es NBC.com haciendo trucos con usted. Cuando NBC.com decide que su navegador no es capaz de mostrar PDF, simplemente envía una página web sin importar lo que está solicitando, incluso si no existe.

Necesita volver a engañarlo diciéndole que su navegador es capaz, algo como,

conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13");

3 para la respuesta № 5

Basado en las respuestas e información dadas en la pregunta, este es el código que debe usar:

public static boolean doesURLExist(URL url) throws IOException
{
// We want to check the current URL
HttpURLConnection.setFollowRedirects(false);

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

// We don"t need to get data
httpURLConnection.setRequestMethod("HEAD");

// Some websites don"t like programmatic access so pretend to be a browser
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
int responseCode = httpURLConnection.getResponseCode();

// We only accept response code 200
return responseCode == HttpURLConnection.HTTP_OK;
}

Por supuesto probado y funcionando.