웹사이트 검색

Apache HttpClient 예제 - CloseableHttpClient


Apache HttpClient를 사용하여 클라이언트 코드에서 서버로 HTTP 요청을 보낼 수 있습니다. 지난 튜토리얼에서는 HttpURLConnection을 사용하여 Java 프로그램 자체에서 GET 및 POST HTTP 요청 작업을 수행하는 방법을 살펴보았습니다. 오늘 우리는 동일한 예제 프로젝트를 사용하지만 Apache HttpClient를 사용하여 GET 및 POST 요청 작업을 수행합니다.

아파치 Http클라이언트

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.4</version>
</dependency>

그러나 Maven을 사용하지 않는 경우 작동하려면 프로젝트 빌드 경로에 다음 jar를 추가해야 합니다.

  1. httpclient-4.4.jar
  2. httpcore-4.4.jar
  3. commons-logging-1.2.jar
  4. commons-codec-1.9.jar

  1. 도우미 클래스 HttpClients를 사용하여 CloseableHttpClient의 인스턴스를 만듭니다.
  2. HTTP 요청 유형에 따라 HttpGet 또는 HttpPost 인스턴스를 만듭니다.
  3. addHeader 메서드를 사용하여 User-Agent, Accept-Encoding 등과 같은 필수 헤더를 추가합니다.
  4. POST의 경우 NameValuePair 목록을 만들고 모든 양식 매개변수를 추가합니다. 그런 다음 HttpPost 엔터티로 설정합니다.
  5. HttpGet 또는 HttpPost 요청을 실행하여 CloseableHttpResponse를 가져옵니다.
  6. 응답에서 상태 코드, 오류 정보, 응답 html 등과 같은 필수 세부 정보를 가져옵니다.
  7. 마지막으로 apache HttpClient 리소스를 닫습니다.

다음은 Java 프로그램 자체에서 HTTP GET 및 POST 요청을 수행하기 위해 Apache HttpClient를 사용하는 방법을 보여주는 마지막 프로그램입니다.

package com.journaldev.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class ApacheHttpClientExample {

	private static final String USER_AGENT = "Mozilla/5.0";

	private static final String GET_URL = "https://localhost:9090/SpringMVCExample";

	private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";

	public static void main(String[] args) throws IOException {
		sendGET();
		System.out.println("GET DONE");
		sendPOST();
		System.out.println("POST DONE");
	}

	private static void sendGET() throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(GET_URL);
		httpGet.addHeader("User-Agent", USER_AGENT);
		CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

		System.out.println("GET Response Status:: "
				+ httpResponse.getStatusLine().getStatusCode());

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				httpResponse.getEntity().getContent()));

		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = reader.readLine()) != null) {
			response.append(inputLine);
		}
		reader.close();

		// print result
		System.out.println(response.toString());
		httpClient.close();
	}

	private static void sendPOST() throws IOException {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(POST_URL);
		httpPost.addHeader("User-Agent", USER_AGENT);

		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		urlParameters.add(new BasicNameValuePair("userName", "Pankaj Kumar"));

		HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
		httpPost.setEntity(postParams);

		CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

		System.out.println("POST Response Status:: "
				+ httpResponse.getStatusLine().getStatusCode());

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				httpResponse.getEntity().getContent()));

		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = reader.readLine()) != null) {
			response.append(inputLine);
		}
		reader.close();

		// print result
		System.out.println(response.toString());
		httpClient.close();

	}

}

위의 프로그램을 실행하면 브라우저에서 받은 것과 유사한 출력 html을 얻습니다.

GET Response Status:: 200
<html><head>	<title>Home</title></head><body><h1>	Hello world!  </h1><P>  The time on the server is March 7, 2015 1:01:22 AM IST. </P></body></html>
GET DONE
POST Response Status:: 200
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Home Page</title></head><body><h3>Hi Pankaj Kumar</h3></body></html>
POST DONE

여기까지가 Apache HttpClient 예제의 전부이며 사용할 수 있는 많은 유틸리티 메서드가 포함되어 있습니다. 따라서 더 나은 이해를 위해 확인하는 것이 좋습니다.