JAVA

HttpResponse와 Unirest를 이용한 외부 데이터 요청

Ambitions 2020. 6. 17. 15:59

최근 개발하면서 외부 API를 이용해서 데이터를 요청해야할 일이 생기게 되어 HttpResponse와 Unirest를 사용해서 개발을 해보았는데, 오늘은 그 내용을 정리해보려고 한다.

 

일단, 회사에서 개발한 내용이였고, 기본적인 maven에 dependency설정은 잡혀있는 상태로 개발을 했는데, Spring으로 개발을 하고 maven을 이용해서 프로젝트 관리를 하고있다면 pom.xml에 다음 내용들을 추가해주면 된다.

       <!-- Unirest -->
        <dependency>
            <groupId>com.mashape.unirest</groupId>
            <artifactId>unirest-java</artifactId>
            <version>1.4.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpasyncclient</artifactId>
            <version>4.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.8</version>
        </dependency>    
		
		<!-- httpcore -->
        <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpcore</artifactId>
          <version>4.4.6</version>
        </dependency>
        
        <!-- httpclient -->
       <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpclient</artifactId>
          <version>4.5.2</version>
       </dependency>
		
        <!-- json obejct -->
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

 

위 내용을 pom.xml에 추가해주고, 혹시모르니 인텔리 j 는 터미널에서 mvn clean install을, 이클립스의 경우 업데이트 프로젝트를 한번 실행해주는게 좋을 것 같다.

 

먼저 Unirest에 대해서 간단하게 설명하면 Unirest는 Mashape의 경량 HTTP 클라이언트 라이브러리이며, Spring 외에 ruby, python, .net 계열에서도 사용할 수 있다고 한다.

Unirest는 post, get, put, delete 등 기본적인 4가지 요청 외에 patch, options까지 지원한다고 한다. 

외에 특이한점으로 asJsonAsync, asBinaryAsync등의 메소드를 이용해서 비동기식 요청도 가능하다고 설명되어 있다.

 

asJsonAsync는 보통 Java Spring환경에서는 사용할 일이 없을 것 같지만 이런 기능이 있다는 것도 알아두면 좋을 것 같다. 또 Unirest를 통해 요청한 결과의 응답은 HttpResponse를 통해 얻을 수 있고, HttpResponse는 getBody, getStatus... 등의 메소드들을 지원하고 있다. 자세한 내용은 코드를 통해 살펴보도록 한다.

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
//import...
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.body.RequestBodyEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import java.io.File;
import java.util.HashMap;
import java.util.Map;
 
//클래스생략
 
public void postTest() throws UnirestException {
 
        String url = "api/test/insert.do";
        Map<StringString> header = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        header.put("Content-Type""application/json");
        params.put("id""1234");
        params.put("name""test");
 
        /**
         * Unirest에서 파라미터를 전달하는 메소드는 4가지가 있는데
         * 각각 queryString, field, routeParam, body를 이용할 수 있다
         */
 
        HttpResponse<String> resultForString = Unirest.post(url).headers(header).queryString(params).asString(); // 문자열로 파라미터를 전달 후 응답을 String형으로 받거나, Json형태로 받을 수 있다.
        HttpResponse<JsonNode> resultForJson = Unirest.post(url).headers(header).queryString(params).asJson(); // 문자열로 파라미터를 전달 후 응답을 String형으로 받거나, Json형태로 받을 수 있다.
        Unirest.post(url).headers(header).field("file"new File("/file/file1234.jpg")); // front-end 기준 formData / Back-End기준 multipartRequest를 이용하는 것 처럼(파일전송가능)
        String rurl = "api/test/insert.do/{id}";
        Unirest.post(rurl).headers(header).routeParam("id""id"); // url의 선언된 파라미터와 매핑되어 사용 위의 rurl처럼 사용해야함
        Unirest.post(url).headers(header).body(params); // Json형태로 파라미터를 보낼 때 사용
 
        //응답결과
        System.out.println(resultForString.getBody()); // 응답결과
        System.out.println(resultForString.getHeaders()); // 응답헤더
        System.out.println(resultForString.getStatus()); // 응답상태
    }
cs

실제 내가 적용한 방법은 QuesyString을 이용했고, body와 routeParam의 경우 확장성을 고려했을 때 별로 좋은 방법이 아니라고 생각했기에 사용하지는 않았지만 추후 사용할 일이 있을지도 몰라서 정리해두었다.

 

위 코드는 설명 및 정리를 위해 작성된 코드이며, 실제로 동작하는지는 테스트는 해보지 않았다. (실제 내가 개발한 기능에서는 위 코드와 비슷하게 작성하였다.), 또 위 코드에서는 예외처리를 메소드에 상속시켜버렸지만, 실제 서비스될 코드에서는 별도의 예외처리 로직을 작성하는 것이 좋다.