2012-08-27 16 views

risposta

6

Utilizzare la chiamata HEAD. È fondamentalmente una chiamata GET in cui il server non restituisce un corpo. Esempio da loro documentazione:

HeadMethod head = new HeadMethod("http://jakarta.apache.org"); 
// execute the method and handle any error responses. 
... 
// Retrieve all the headers. 
Header[] headers = head.getResponseHeaders(); 

// Retrieve just the last modified header value. 
String lastModified = head.getResponseHeader("last-modified").getValue(); 
0

È possibile utilizzare:

HeadMethod head = new HeadMethod("http://www.myfootestsite.com"); 
head.setFollowRedirects(true); 

// Header stuff 
Header[] headers = head.getResponseHeaders(); 

Facciamo in modo che il server web supporta il comando HEAD.

vedi sezione 9.4 nella HTTP 1.1 Spec

0

È possibile ottenere queste informazioni con java.net.HttpURLConnection:

URL url = new URL("http://stackoverflow.com/"); 
URLConnection urlConnection = url.openConnection(); 
if (urlConnection instanceof HttpURLConnection) { 
    int responseCode = ((HttpURLConnection) urlConnection).getResponseCode(); 
    switch (responseCode) { 
    case HttpURLConnection.HTTP_OK: 
     // HTTP Status-Code 302: Temporary Redirect. 
     break; 
    case HttpURLConnection.HTTP_MOVED_TEMP: 
     // HTTP Status-Code 302: Temporary Redirect. 
     break; 
    case HttpURLConnection.HTTP_NOT_FOUND: 
     // HTTP Status-Code 404: Not Found. 
     break; 
    } 
} 
8

Ecco come ottengo il codice di stato da HttpClient, che mi piace molto:

public boolean exists(){ 
    CloseableHttpResponse response = null; 
    try { 
     CloseableHttpClient client = HttpClients.createDefault(); 
     HttpHead headReq = new HttpHead(this.uri);      
     response = client.execute(headReq);   
     StatusLine sl = response.getStatusLine();   
     switch (sl.getStatusCode()) { 
      case 404: return false;      
      default: return true;      
     }   

    } catch (Exception e) { 
     log.error("Error in HttpGroovySourse : "+e.getMessage(), e); 
    } finally { 

     try { 
      response.close(); 
     } catch (Exception e) { 
      log.error("Error in HttpGroovySourse : "+e.getMessage(), e); 
     } 
    }  

    return false; 
} 
+1

Grazie per aver fornito un esempio CloseableHttpResponse. "404" è una specie di numero magico - si potrebbe invece usare la classe HttpStatus di Apache switch (sl.getStatusCode()) { case HttpStatus.SC_CREATED: return false; predefinito: return true; } –

Problemi correlati