[java] HttpClient를 사용하여 웹 페이지에 GET 요청하는 방법은?

Java에서 HttpClient를 사용하여 웹 페이지에 GET 요청을 보내는 방법에 대해 알아보겠습니다.

  1. HttpClient 의존성 추가 먼저, HttpClient를 사용하기 위해 HttpClient 의존성을 프로젝트에 추가해야 합니다. Maven을 사용하는 경우, pom.xml 파일에 아래의 의존성을 추가합니다.
<dependencies>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
    </dependency>
</dependencies>
  1. HttpClient 객체 생성 및 GET 요청 보내기 HttpClient 객체를 생성하고, HTTP GET 요청을 보내기 위해 HttpGet 객체를 생성합니다.
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;

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

        try {
            HttpResponse response = httpClient.execute(httpGet);
            System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

위의 예제에서는 “http://www.example.com”에 대한 GET 요청을 보내고, 응답 상태 코드를 출력합니다.

  1. 응답 처리 실제 서버 응답을 받았을 때 응답 데이터를 처리해야 하는 경우, HttpResponse 객체에는 다양한 정보가 포함되어 있습니다. 예를 들어, 응답 본문 데이터를 가져오려면 아래와 같이 처리할 수 있습니다.
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;

// ...

try {
    // ...

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        String responseBody = EntityUtils.toString(entity);
        System.out.println("Response Body: " + responseBody);
    }
} catch (Exception e) {
    e.printStackTrace();
}

위의 예제에서는 응답 본문 데이터를 문자열로 변환하여 출력하는 방법을 보여줍니다.

HttpClient를 사용하여 웹 페이지에 GET 요청을 보내는 방법에 대해서 알아보았습니다. HttpClient를 사용하면 HTTP 요청을 쉽게 보낼 수 있으며, 응답을 처리하는 다양한 방법을 적용할 수 있습니다.

더 자세한 내용은 HttpClient 공식 문서를 참조하십시오.