본문 바로가기
Today I learned

2020 10 05

by soheemon 2020. 10. 5.

HttpUrlConnection 객체가 200외의 에러를 반환한다면 inputStream을 read시도시 Exception이 발생하는데,

에러 발생 원인이 ResponseBody안에 json형태로 담겨있다면 이 오류를 봐야만 한다.

200외의 에러일때 ResponseBody 가져오는법

HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
InputStream _is;
if (httpConn.getResponseCode() >= 400) {
    _is = httpConn.getInputStream();
} else {
     /* error from server */
    _is = httpConn.getErrorStream();
}

//응용

HttpURLConnection httpConn = (HttpURLConnection)_urlConnection;
JSONObject json = new JSONObject();		//request body..
String paramString = json.toString(); 
byte[] postDataBytes = paramString.getBytes("UTF-8");

/*필요시 property setting.. requestMethod setting... */

httpConn.getOutputStream().write(postDataBytes);
InputStream _is;
if (httpConn.getResponseCode() >= 400) {
    _is = httpConn.getInputStream();
    //버퍼에 Response body를 담는다
} else {
     /* error from server */
    _is = httpConn.getErrorStream();
    //버퍼에 Response body를 담는다
    return responseBody..;	//fail
}

출처: coderanch.com/t/433447/java/HttpsURLConnection-Reading-Body-Response-response

'Today I learned' 카테고리의 다른 글

2020 10 13  (0) 2020.10.13
2020 10 07  (0) 2020.10.07
2020 10 04  (0) 2020.10.04
2020 10 03  (0) 2020.10.03
2020 10 02  (0) 2020.10.02

댓글