고똘이의 IT 개발이야기

백엔드 개발을 진행할때 프론트 서버와 API 서버를 따로 분리 하거나 혹은 다른 회사의 REST API를 호출해야 합니다. 그럴경우 API 서버의 METHOD에 맞게 Http를 사용하여 호출하여야 합니다.

 

 

아래의 소스 예제의 경우 GET, POST, PUT, DELETE를 사용 할 수 있습니다. callApi method를 호출 시 type에 REST API의 METHOD 타입을 설정해 주시면 됩니다.

데이터를 담아서 호출 할 경우 JSON 형식의 데이터로 셋팅 후 호출 하시면 됩니다. 기본적인 WEB APPLICATION 방식으로 예제를 들어 보겠습니다.

 

1. 컨트롤러에서 특정 API를 호출 합니다. HTTP METHOD 방식은 POST로 하겠습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
@Controller
public class MainController {    
    
    @GetMapping("/main")
    public String mainIndexPage() {
        
        JsonObject param = new JsonObject();
        // POST 방식으로 호출.(GET, POST, PUT, DELETE 다 가능 합니다.)
        HttpUtil.callApi(param, "POST");
        
        return "/tiles/view/main";
    }
}

 

2. REST API에 같이 보낼 데이터를 JSON 타입으로 셋팅 후 호출을 합니다. 호출 후 응답 데이터 타입도 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public class HttpUtil {
 
    public static void callApi(JsonObject params, String type){
        
        HttpURLConnection conn = null;
        JSONObject responseJson = null;
        
        try {
            //URL 설정
            URL url = new URL("http://localhost:8080/test/api/action");
 
            conn = (HttpURLConnection) url.openConnection();
            
            // type의 경우 POST, GET, PUT, DELETE 가능
            conn.setRequestMethod(type);
            conn.setRequestProperty("Content-Type""application/json");
            conn.setRequestProperty("Transfer-Encoding""chunked");
            conn.setRequestProperty("Connection""keep-alive");
            conn.setDoOutput(true);
            
            
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
            // JSON 형식의 데이터 셋팅
            JsonObject commands = new JsonObject();
            JsonArray jsonArray = new JsonArray();
            
            params.addProperty("key"1);
            params.addProperty("age"20);
            params.addProperty("userNm""홍길동");
 
            commands.add("userInfo", params);
             // JSON 형식의 데이터 셋팅 끝
            
            // 데이터를 STRING으로 변경
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String jsonOutput = gson.toJson(commands);
                 
            bw.write(commands.toString());
            bw.flush();
            bw.close();
            
            // 보내고 결과값 받기
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                 BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                responseJson = new JSONObject(sb.toString());
                
                // 응답 데이터
                System.out.println("responseJson :: " + responseJson);
            } 
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            System.out.println("not JSON Format response");
            e.printStackTrace();
        }
    }
}

 

위의 소스에서 대략적인 설명을 다해놔서 따로 소스에 대해서 설명 드릴거는 없을거 같습니다. 따로 궁금한 사항이 있으시면 댓글로 남겨 주시면 바로 답변 드리겠습니다.

 

 

 

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band