HTTP 란? - HTTP-1

Kim taegwan·2026년 4월 1일

HTTP 메서드

서버에게 무엇을 원하는지 알려주는 방법입니다.

메서드의미예시
GET데이터를 가져옴게시글 조회, 검색
POST데이터를 전송회원가입, 글 작성
PUT데이터를 수정프로필 수정
DELETE데이터를 삭제게시글 삭제

HTTP 상태 코드

서버가 요청을 처리한 결과를 숫자로 알려줍니다.

코드의미
200성공
201생성 성공 (POST 요청 후)
400잘못된 요청
403접근 권한 없음
404찾을 수 없음
500서버 내부 오류

자바로 HTTP GET 요청 보내기

자바는 HttpURLConnection 클래스로 HTTP 통신을 합니다. I/O 단원에서 배운 BufferedReader 가 여기서도 그대로 등장합니다.

실습 주소

https://jsonplaceholder.typicode.com/posts/1

이 주소는 가짜 데이터를 제공하는 무료 테스트 API 입니다. 아래와 같은 JSON 데이터를 응답으로 돌려줍니다.

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere...",
  "body": "quia et suscipit..."
}
package http.ch01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

// https://jsonplaceholder.typicode.com/todos/1
public class SimpleHttpClient {

    public static void main(String[] args) {

        // 자바로 HTTP 요청과 응답 만들어 보기
        String urlString = "https://jsonplaceholder.typicode.com/todos/10";
        // String urlString = "https://www.naver.com/";
        // HTTP 통신하는 클래스
        HttpURLConnection connection = null;


        try {
            // 1단계 : URL 객체 생성
            URL url = new URL(urlString);

            // 2단계 : HTTP 연결 객체 생성
            connection = (HttpURLConnection)url.openConnection();

            // 3단계 : 요청 방식 설정 (GET, POST, PUT, DELETE)
            // 자원에 요청 --> GET 던져야 함.
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");

            // 4단계 : 실제 요청 전송 --> 서버 ---> 즉시 응답 --> (응답 코드)
            int responseCode = connection.getResponseCode();
            System.out.println("응답 코드 확인 : " + responseCode);

            if(responseCode != 200) {
                System.out.println("요청 실패!");
                return;
            }

            // 5단계 : 응답 본문 읽기
            // I/O 단원에서 배운 체인 그대로 사용 가능

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()))) {

                // 문자가 많을 때 StringBuffer 를 사용하는게 좋다
                StringBuffer response = new StringBuffer();
                String line;
                while ( (line = reader.readLine()) != null ) {
                    response.append(line).append("\n");
                }

                System.out.println("응답 내용 : ");
                System.out.println(response.toString());
            }

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(connection != null) {
                connection.disconnect();
            }
        }

    } // end of main

}

URL 객체가 필요한 이유

문자열은 그냥 문자열입니다. "https://jsonplaceholder.typicode.com/todos" 는 자바 입장에서 그냥 긴 문자열 하나입니다.

이 문자열만으로는 HTTP 연결을 만들 수 없습니다. HttpURLConnection 은 URL 객체를 요구하기 때문입니다.

// HttpURLConnection 은 URL 객체를 받음
connection = (HttpURLConnection) url.openConnection(); // URL 객체 필요

URL 객체 안에서 무슨 일이 일어나나요? new URL(urlString) 을 호출하면 URL 이 각 부분으로 파싱됩니다.

파싱(parsing)은 "문자열을 의미 있는 조각으로 분해해서 구조화된 데이터로 만드는 것"입니다.

new URL("https://www.example.com:8080/path?q=hello#section") 을 호출하면 자바가 이 문자열을 읽고 각 부분의 의미를 파악해서 내부 필드에 저장합니다.

URL url = new URL("https://jsonplaceholder.typicode.com/todos?page=1");

url.getProtocol(); // "https"
url.getHost();     // "jsonplaceholder.typicode.com"
url.getPath();     // "/todos"
url.getQuery();    // "page=1"
url.getPort();     // -1 (기본 포트 443 사용)

"https://jsonplaceholder.typicode.com/todos?page=1"
  ↓
URL 객체 파싱
  ↓
프로토콜 : https
호스트   : jsonplaceholder.typicode.com
경로     : /todos
쿼리     : page=1
포트     : 443 (https 기본값)

왜 문자열을 직접 안 쓰고 객체로 만드나요?

// 문자열로는 이게 불가능
String urlString = "https://jsonplaceholder.typicode.com/todos";
urlString.openConnection(); // 문자열에는 이런 메서드 없음

// URL 객체는 가능
URL url = new URL(urlString);
url.openConnection(); // TCP 소켓 연결 생성

핵심 요약

HTTP
  웹에서 데이터를 주고받기 위한 통신 규칙
  TCP 소켓 위에서 동작
  클라이언트 요청 → 서버 응답 구조

HTTP 메서드
  GET(조회), POST(전송), PUT(전체 교체), DELETE(삭제)
  부분 수정은 PATCH 가 담당 (스프링 부트에서 다룸는 내용)

HTTP 상태 코드
  200(성공), 404(없음), 500(서버 오류)

HttpURLConnection
  자바에서 HTTP 통신하는 클래스
  getResponseCode() 호출 시 실제 요청 전송
  Closeable 미구현 → try-with-resources 불가, finally 로 disconnect()
  Java 11 이상에서는 HttpClient (java.net.http) 가 대안 → Closeable 구현, 현대적 API

0개의 댓글