HttpClient를 이용해 GET request 보내기


Apache HttpClient를 이용하면 간편하게 HTTP request를 보낼 수 있습니다.

간혹 웹 서버를 만들면서 다른 서버로 보터 request를 보내 response 받아 데이터를 처리해야

할 때가 있는데 이 때 HttpClient를 이용하면 간단하게 구현 가능합니다.



Mavan을 이용한 dependency 설정


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


*Maven과 같은 빌드툴 이용하지 않는다면 https://hc.apache.org/downloads.cgi을 통해 직접 jar파일을 다운 후 

빌드 패스에 추가해주시면 됩니다.



Dependency 설정을 하셨다면 이제 어떤 순서대로 코딩할지 살펴보겠습니다.


1. ClosableHttpClient 인스턴스를 생성

2. HTTP request type에 따른 HttpGet/HttpPost 인스턴스 생성

3. addHeader 메서드를 이용해 헤더정보 추가

4. request를 execute해서 CloseableHttpResponse 얻기

5. response 출력

6. close 메서드를 통해 연결 종료




1. ClosableHttpClient 인스턴스 생성

1
2
3
4
5
6
7
8
9
10
11
public class Httpclient1 {
    
    private static final String USER_AGENT = "Mozila/5.0";
    private static final String GET_URL = "http://www.google.com";    
 
    public static void sendGet() throws ClientProtocolException, IOException {
        
        //http client 생성
        CloseableHttpClient httpClient = HttpClients.createDefault();
    }
}
cs


2. HTTP request type에 따른 HttpGet/HttpPost 인스턴스 생성


1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Httpclient1 {
    
    private static final String USER_AGENT = "Mozila/5.0";
    private static final String GET_URL = "http://www.google.com";    
 
    public static void sendGet() throws ClientProtocolException, IOException {
        
        //http client 생성
        CloseableHttpClient httpClient = HttpClients.createDefault();
 
        //get 메서드와 URL 설정
        HttpGet httpGet = new HttpGet(GET_URL);
    }
}
cs



3. addHeader 메서드를 이용해 헤더정보 추가


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Httpclient1 {
    
    private static final String USER_AGENT = "Mozila/5.0";
    private static final String GET_URL = "http://www.google.com";    
 
    public static void sendGet() throws ClientProtocolException, IOException {
        
        //http client 생성
        CloseableHttpClient httpClient = HttpClients.createDefault();
 
        //get 메서드와 URL 설정
        HttpGet httpGet = new HttpGet(GET_URL);
 
        //agent 정보 설정
        httpGet.addHeader("User-Agent", USER_AGENT);
    }
}
cs



여기까지 했으면 이제는 excute메서드를 통해 request를 보내주고 받은 응답을 처리하면 됩니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class Httpclient1 {
    
    private static final String USER_AGENT = "Mozila/5.0";
    private static final String GET_URL = "http://www.google.com";    
 
    public static void sendGet() throws ClientProtocolException, IOException {
        
        //http client 생성
        CloseableHttpClient httpClient = HttpClients.createDefault();
 
        //get 메서드와 URL 설정
        HttpGet httpGet = new HttpGet(GET_URL);
 
        //agent 정보 설정
        httpGet.addHeader("User-Agent", USER_AGENT);
        
        //get 요청
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        
        System.out.println("::GET Response Status::");
        
        //response의 status 코드 출력
        System.out.println(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();
    }
}
cs



실행결과




*json 데이터를 GET request를 통해 받아와야 하는 경우가 많습니다.

그 때에는 Header 정보인 Content-type에 'application/json'을 추가하고 요청을 보내면 됩니다.


예제코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.io.IOException;
 
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
public class httpclient2 {
    
    private static final String USER_AGENT = "Mozila/5.0";
    private static final String GET_URL = "https://blockchain.info/ko"
            + "/rawblock/0000000000000bae09a7a393a8acd"
            + "ed75aa67e46cb81f7acaa5ad94f9eacd103";
    
    public static void sendGet() throws ClientProtocolException, IOException {
        
        //http client 생성
        CloseableHttpClient httpClient = HttpClients.createDefault();
        
        //get 메서드와 URL 설정
        HttpGet httpGet = new HttpGet(GET_URL);
        
        //agent 정보 설정
        httpGet.addHeader("User-Agent", USER_AGENT);
        httpGet.addHeader("Content-type""application/json");
        
        //get 요청
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        
        System.out.println("GET Response Status");
        System.out.println(httpResponse.getStatusLine().getStatusCode());
        String json = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        
        System.out.println(json);
        
        httpClient.close();
    }
}
cs


실행결과



참고 : http://www.journaldev.com/7146/apache-httpclient-example-closeablehttpclient

'Java' 카테고리의 다른 글

오버로딩 vs 오버라이딩  (0) 2017.05.16
JAVA 특징와 OOP  (0) 2017.05.12
[Reflect]Refletion의 정의와 동적 메소드 호출  (0) 2017.03.17
[Collection] 동기화된 컬렉션  (0) 2017.03.10
[람다식]메소드와 생성자 참조  (0) 2017.03.08

+ Recent posts