ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 안드로이드에서 Rest API 호출하기
    Android 2019. 5. 30. 23:40

    Rest API

    최근의 안드로이드 앱들은 서버와의 연결이 필수적이다. 과거에는 성능 등의 문제로 Native Server가 쓰이는 경우가 많았지만, 현대에 들어서는 Restful Web API를 통해 서버와 교신을 하는 경우가 늘어났다. 안드로이드 앱은 코틀린으로 작성되었거나 NDK 로 쓰여진 부분을 제외하면 자바 기반으로 쓰여지는데, 다행히 Java는 전통적으로 서버 사이드에 많이 쓰여왔기에 http 형태의 스트림을 처리하기에 알맞은 내장 클래스들을 대부분 가지고 있다. 이번에는 특별한 라이브러리를 쓰지 않고 Java만을 이용해 간단히 Rest API를 호출하는 방법을 살펴보려 한다.

     

    필요한 클래스는 다음과 같다.

    Class Description
    HttpURLConnection HTTP 연결을 만든다
    InputStream HttpURLConnection의 결과를 받는다
    BufferedReader 받은 결과를 Buffer에 쌓는다
    StringBuilder Buffer의 결과를 조합해 최종 결과 스트링을 만든다 

     

    자 이제 준비는 끝났으니, GET 형태의 API를 호출해 보자. 다음 예제는 api.example.com/v1/users라는 API를 호출하는 코드이다. 

     String result = null;
     try {
         // Open the connection
         URL url = new URL("https://api.example.com/v1/users");
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");
         InputStream is = conn.getInputStream();
    
         // Get the stream
         StringBuilder builder = new StringBuilder();
         BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
         String line;
         while ((line = reader.readLine()) != null) {
             builder.append(line);
         }
    
         // Set the result
         result = builder.toString();
     }
     catch (Exception e) {
         // Error calling the rest api
         Log.e("REST_API", "GET method failed: " + e.getMessage());
         e.printStackTrace();
     }

     

    유사한 방식으로 PUT이나 DELETE 등의 API를 호출하는 것이 가능하다. 그런데 안드로이드에서는 한 가지 주의할 점이 있다. 안드로이드의 경우 UI Thread에서 Network 관련 함수를 호출하는 것이 금지되어 있다. UI thread에서 시도하면 관련 exception이 나는 것을 경험할 수 있다. 따로 Thread를 만들어서 사용해도 되지만, AsyncTask로 다음과 같이 간단히 호출이 가능하다.

     

     // Calling the rest api in the UI thread
     proteted void some_method_in_ui_thread() {
         ...
         new RestAPITask("https://api.example.com/v1/users").execute();
         ...
     }
    
     ...
     ...
    
     // Rest API calling task
     public static class RestAPITask extends AsyncTask<Integer, Void, Void> {
         // Variable to store url
         protected String mURL;
    
         // Constructor
         public RestAPITask(String url) {
             mURL = url;
         }
    
         // Background work
         protected void doInBackground(Integer... params) {
             String result = null;
    
             try {
                 // Open the connection
                 URL url = new URL(mURL);
                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                 conn.setRequestMethod("GET");
                 InputStream is = conn.getInputStream();
    
                 // Get the stream
                 StringBuilder builder = new StringBuilder();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                 String line;
                 while ((line = reader.readLine()) != null) {
                     builder.append(line);
                 }
    
                 // Set the result
                 result = builder.toString();
             }
             catch (Exception e) {
                 // Error calling the rest api
                 Log.e("REST_API", "GET method failed: " + e.getMessage());
                 e.printStackTrace();
             }
         }
     }

     

     

    Fin.

    반응형

    댓글

Calvin's Memo