반응형
Http를 사용하여 응답 본문을 가져오는 방법URL 연결, 2xx 이외의 코드가 반환될 때?
서버가 오류를 반환할 경우에 대비하여 Json 응답을 검색하는 데 문제가 있습니다.자세한 내용은 아래를 참조하십시오.
요청 수행 방법
사용하고 있다java.net.HttpURLConnection
요청 속성을 설정하고 다음을 수행합니다.
conn = (HttpURLConnection) url.openConnection();
그 후 요청이 성공하면 Json:
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
return sb.toString();
...문제는 다음과 같습니다.
서버가 50x나 40x와 같은 오류를 반환했을 때 받은 Json을 가져올 수 없습니다.다음 행은 IOException을 슬로우합니다.
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
// throws java.io.IOException: Server returned HTTP response code: 401 for URL: www.example.com
서버는 확실히 본문을 송신합니다.외부 툴의 Burp Suite에 표시됩니다.
HTTP/1.1 401 Unauthorized
{"type":"AuthApiException","message":"AuthApiException","errors":[{"field":"email","message":"Invalid username and/or password."}]}
응답 메시지(즉, "내부 서버 오류")와 코드(즉, "500")를 다음 방법으로 얻을 수 있습니다.
conn.getResponseMessage();
conn.getResponseCode();
하지만 요청 본문을 가져올 수 없습니다...도서관에서 눈치채지 못한 방법이 있지 않을까?
응답 코드가 200 또는 2xx가 아닌 경우getErrorStream()
대신getInputStream().
오류에 잘못된 메서드가 사용되었습니다. 작업 코드는 다음과 같습니다.
BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
이것은 서버로부터 PHP 에코와 같은 응답을 얻을 수 있는 간단한 방법입니다.그렇지 않으면 에러 메시지가 표시됩니다.
BufferedReader br = null;
if (conn.getResponseCode() == 200) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String strCurrentLine;
while ((strCurrentLine = br.readLine()) != null) {
System.out.println(strCurrentLine);
}
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String strCurrentLine;
while ((strCurrentLine = br.readLine()) != null) {
System.out.println(strCurrentLine);
}
}
언급URL : https://stackoverflow.com/questions/25011927/how-to-get-response-body-using-httpurlconnection-when-code-other-than-2xx-is-re
반응형
'programing' 카테고리의 다른 글
apache error.log의 "notice" child pid XXXX 종료 신호 Segmentation fault (11)" (0) | 2022.09.14 |
---|---|
Composer를 사용하여 특정 버전의 패키지를 설치하는 방법 (0) | 2022.09.14 |
'str' 개체가 품목 할당을 지원하지 않습니다. (0) | 2022.09.14 |
항아리 내의 파일 수정 (0) | 2022.09.14 |
HTML 파일은 소스만 보는 것이 아니라 GitHub에서 직접 실행할 수 있습니까? (0) | 2022.09.14 |