2013-02-21 2 views
2

현재 REST 구현을 테스트 중입니다. 나는 문제가있다. 404 오류가 ("User not found"와 같이) 보내 진다면 나는 정확한 HTP-Header를 얻을 수 있지만, 페이지의 body/content는 얻을 수 없다.Grails/Java로 404 본문 얻기

브라우저에서 페이지를 호출하면 생성 된 JSON 콘텐츠를 볼 수 있습니다.

URLConnection connection = new URL(url).openConnection() 
    connection.connect() 

    if (connection instanceof HttpURLConnection) { 
     HttpURLConnection httpConnection = (HttpURLConnection) connection 
     int code = httpConnection.getResponseCode() 
     if (code >= 400) { 
      assertTrue("Wrong Error Code", code == 404) 
     } 
    } 

이것은 잘 작동하는 현재 코드입니다. 하지만 HTTP 응답의 본문을 얻으려면 어떻게해야합니까?

답변

2

는 :

def url = 'http://www.google.com/notfound' 

URLConnection connection = new URL(url).openConnection() 
int code = connection.responseCode 
if(code >= 400) { 
    assert code == 404, "Wrong Error Code (expected 404)" 
    println connection.errorStream.text 
} 
1

InputStream is = conn.getInputStream(); String ur = conn.getURL(). toString();

당신은 오류 스트림에서 내용을 얻을 수 있습니다
+4

나는 (404 에러) 페이지의 입력 스트림을 열 경우이 때문에 작동하지 않습니다 나는'java.io 패키지를 얻을 수 FileNotFoundException' (전에 시도한!) –

관련 문제