[java] HttpClient를 사용하여 웹 사이트에서 특정 페이지를 여러 번 요청하는 방법은?
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
  
public class Main {
    public static void main(String[] args) {
  
        // HttpClient 객체 생성
        HttpClient httpClient = HttpClientBuilder.create().build();
  
        // 요청할 URL
        String url = "https://www.example.com/mypage";
  
        // 페이지를 여러 번 요청하기 위한 반복문
        for (int i = 0; i < 5; i++) {
            try {
                // HttpGet 객체 생성 및 URL 설정
                HttpGet getRequest = new HttpGet(url);
  
                // 요청 실행
                HttpResponse response = httpClient.execute(getRequest);
  
                // 응답 데이터 가져오기
                HttpEntity entity = response.getEntity();
                String responseString = EntityUtils.toString(entity, "UTF-8");
  
                // 응답 출력
                System.out.println("Response: " + responseString);
  
                // 연결 종료
                getRequest.releaseConnection();
  
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

위 코드는 Apache HttpClient를 사용하여 특정 웹사이트의 페이지를 여러 번 요청하는 방법을 보여줍니다. 코드는 다음과 같은 단계로 구성됩니다:

  1. HttpClient 객체를 생성합니다.
  2. 요청할 URL을 지정합니다.
  3. 페이지를 여러 번 요청하기 위해 반복문을 사용합니다.
  4. 요청을 보내고, 응답을 받은 후, 응답 데이터를 가져옵니다.
  5. 응답을 출력하고, 연결을 종료합니다.

이 코드는 Java 8 이상에서 실행할 수 있습니다.

참고 문서: