1.
HttpURLConnection 객체 생성: url.openConnection() 메서드를 사용하여 HttpURLConnection 객체를 생성합니다. 이렇게 생성한 객체를 통해 URL과의 연결을 설정하고 HTTP 요청을 보낼 수 있습니다.
2.
연결 설정 및 요청 전송: urlConnection.connect() 메서드를 호출하여 서버와의 연결을 설정하고 HTTP 요청을 보냅니다.
3.
데이터 수신: urlConnection.getInputStream() 메서드를 사용하여 서버로부터 데이터를 읽어오는 입력 스트림(InputStream)을 얻습니다. BufferedInputStream으로 데이터를 읽어오도록 래핑하고, BufferedReader를 사용하여 문자열 형태로 데이터를 읽어옵니다.
4.
데이터 읽기: br.readLine() 메서드를 사용하여 한 줄씩 데이터를 읽어오며, while 루프를 통해 모든 데이터를 읽어옵니다. 읽은 데이터를 result 변수에 누적합니다.
5.
자원 해제: 데이터 읽기 작업이 끝나면 BufferedReader, BufferedInputStream, 그리고 HttpURLConnection을 각각 close() 메서드를 호출하여 자원을 해제합니다.
이 코드는 주로 HTTP GET 요청을 보내고 응답 데이터를 받아오는 경우에 사용됩니다. 주의해야 할 점은 네트워크 작업은 예외가 발생할 수 있으므로 예외 처리를 적절히 해주어야 합니다. 또한, 데이터 수신이 끝나면 close() 메서드를 통해 연결과 스트림을 반드시 닫아주어야 합니다. 위 코드에서는 finally 블록을 사용하여 자원 해제를 보장하고 있습니다.
해당 내용으로 반영된
내가 작성한 예시 코드이다.
HttpURLConnection connection = null;
BufferedInputStream inputStream = null;
BufferedReader bufferedReader = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.connect();
inputStream = new BufferedInputStream(connection.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
// 사용자가 원하는 처리 작업 (response에 저장된 데이터 활용 등)
// ...
} catch (IOException e) {
log.debug("Connection Error!");
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStream != null) {
inputStream.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (IOException e) {
log.debug("Error while closing resources!");
}
}