2012-08-27 8 views

答えて

6

HEADコールを使用してください。これは、基本的にGETコールであり、サーバーはボディを返さない。そのドキュメントからの例:

あなたが使用することができます
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

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

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

は、WebサーバーがHEADコマンドをサポートしていることを確認しています。 HTTP 1.1 Spec

0

節を参照してください9.4あなたは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

は、私はとても気に入っている、私はHttpClientをからステータスコードを取得する方法である:

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

CloseableHttpResponseの例を提供していただきありがとうございます。 "404"はまあまあですが、代わりにApacheのHttpStatusクラスを使用できます。 switch(sl.getStatusCode()){ case HttpStatus.SC_CREATED:falseを返します。 デフォルト:trueを返します。 } –

関連する問題