[java] HttpClient를 사용하여 웹 서버에서 받은 응답의 헤더를 확인하는 방법은?
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class HttpClientExample {

    public static void main(String[] args) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet("https://www.example.com");

        HttpResponse response = httpClient.execute(httpGet);

        // 응답의 헤더 얻기
        org.apache.http.Header[] headers = response.getAllHeaders();
        for (org.apache.http.Header header : headers) {
            System.out.println(header.getName() + ": " + header.getValue());
        }

        // 응답의 바디 얻기
        String responseBody = EntityUtils.toString(response.getEntity());
        System.out.println(responseBody);
    }
}

위의 예제에서는 HttpClient를 사용하여 “https://www.example.com”에 GET 요청을 보내고 응답을 받습니다. HttpResponse 객체를 통해 응답의 헤더를 확인할 수 있습니다. getAllHeaders() 메서드를 사용하여 모든 헤더를 배열로 얻어올 수 있습니다. 각 헤더의 이름과 값을 출력하여 확인할 수 있습니다.

응답의 바디 역시 받아올 수 있습니다. EntityUtils.toString() 메서드를 사용하여 응답의 바디를 문자열로 얻어올 수 있습니다.

HttpClient의 사용에는 추가적인 의존성이 필요할 수 있으므로, Maven이나 Gradle 등의 의존성 관리 도구를 통해 필요한 의존성을 추가해야 합니다.

참고 자료: