본문 바로가기
언어, 환경별 예제 코드

Java에서 API 호출 후, Error Body 조회하는 방법

by kakao-TAM 2024. 10. 17.

카카오 디벨로퍼스에서 제공하는 API는 에러 발생 시, 문제 해결을 위한 에러코드와 에러메시지 JSON 응답을 전달합니다. 

 

ex)

{“msg”:“NotRegisteredUserException”,“code”:-101}

 

	public String Call(String method, String reqURL, String header, String param) {
		String result = "";
		try {
			String response = "";
			URL url = new URL(reqURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(method);
            conn.setRequestProperty("Authorization", header);
            if(param != null) {
            	System.out.println("param : " + param);
            	conn.setDoOutput(true);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
                bw.write(param);
                bw.flush();            	
                
            }
            int responseCode = conn.getResponseCode();
            System.out.println("responseCode : " + responseCode);
            
            System.out.println("reqURL : " + reqURL);
            System.out.println("method : " + method);
            System.out.println("Authorization : " + header);            
			InputStream stream = conn.getErrorStream();
		    if (stream != null) {
			    try (Scanner scanner = new Scanner(stream)) {
			        scanner.useDelimiter("\\Z");
			        response = scanner.next();
			    }			
			    System.out.println("error response : " + response);
		    }
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = "";
			while ((line = br.readLine()) != null) {
				result += line;
			}
			System.out.println("response body : " + result);
			
			br.close();
		} catch (IOException e) {
			return e.getMessage();
		}
		return result;
	}

 

Webclient 로 API 호출 시, 아래 내용을 참고합니다.

https://stackoverflow.com/questions/44593066/spring-webflux-webclient-get-body-on-error

 

Spring Webflux : Webclient : Get body on error

I am using the webclient from spring webflux, like this : WebClient.create() .post() .uri(url) .syncBody(body) .accept(MediaType.APPLICATION_JSON) ...

stackoverflow.com

 

댓글