Jaka jest najszybsza metoda uzyskiwania statusu adresów URL za pomocą HttpClient? Nie chcę pobierać strony/pliku, chcę tylko wiedzieć, czy strona/plik istnieje? (Jeśli jest to przekierowanie Chcę, aby śledzono przekierowanie)Jaki jest najszybszy sposób uzyskania kodu statusu adresu URL za pomocą HttpClient
7
A
Odpowiedz
6
Użyj połączenia HEAD. Jest to po prostu wywołanie GET, w którym serwer nie zwraca ciała. Przykład z ich dokumentacją:
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
Można użyć:
HeadMethod head = new HeadMethod("http://www.myfootestsite.com");
head.setFollowRedirects(true);
// Header stuff
Header[] headers = head.getResponseHeaders();
Czy upewnij się, że twój serwer obsługuje polecenia głowy.
Patrz punkt 9.4 w HTTP 1.1 Spec
0
Można uzyskać te informacje z 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
Oto jak uzyskać kod stanu z HttpClient, które bardzo lubię:
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;
}
Dziękujemy za podanie przykładu CloseableHttpResponse. "404" jest jednak trochę magiczną liczbą - można zamiast tego użyć parametru Apache HttpStatus klasy (sl.getStatusCode()) { case HttpStatus.SC_CREATED: return false; default: return true; } –