2012-08-27 2 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(); 

는 웹 서버가 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를 반환합니다. } –

관련 문제