2009-09-04 3 views
64
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"); 
} 

Questo dovrebbe stampareCome verificare se un URL esiste o restituisce 404 con Java?

exists 
does not exists 

TEST

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"));   

uscita

SOLUZIONE

aggiungere la riga successiva prima .connect() e l'uscita sarebbe 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)"); 
+0

Non vedo il problema nel test. Nel mio browser non ottengo contenuti per il secondo risultato, ma non ottengo un 404 –

+0

In effetti, mi sembra di ottenere una pagina HTML in gran parte vuota –

+1

Quel sito Web sembra offrire contenuti validi per quasi tutto. per esempio. www.nbc.com/junk. Prova con http://www.example.com/junk.html –

risposta

24

Usa HttpUrlConnection chiamando openConnection() sul vostro oggetto URL.

getResponseCode() ti darà la risposta HTTP dopo aver letto dalla connessione.

ad es.

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(); 

(non testato)

+0

Ho aggiornato il mio codice con un test fallito –

+2

Non funziona! –

12

Non c'è niente di sbagliato con il codice. È la NBC.com a fare brutti scherzi. Quando NBC.com decide che il tuo browser non è in grado di visualizzare PDF, semplicemente rimanda una pagina web indipendentemente da ciò che stai richiedendo, anche se non esiste.

È necessario ingannare indietro dicendo che il browser è in grado, qualcosa di simile,

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"); 
53

Si consiglia di aggiungere

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

se non si vuole seguire il reindirizzamento (3XX)

Invece di fare un "GET", un "HEAD" è tutto ciò che serve.

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

+1 per l'HEAD, le persone dimenticano come funziona ogni tanto l'HTTP ed è bello che alcune persone lo ricordino ancora :) –

+0

Gestire gli URL HTTPS è più complicato vero? Devo gestire i certificati ... – Jayy

36

questo ha funzionato per me:

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); 

grazie per i suggerimenti di cui sopra.

1

Sulla base delle risposte date e le informazioni in questione, questo è il codice si dovrebbe usare:

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; 
} 

Naturalmente testati e funzionanti.