Web & Mobile/Android

[Android] REST API 호출

byunghyun23 2024. 3. 8. 22:58

Flask REST API 구현과 연관된 포스팅입니다.

 

Java 기반 REST API 호출 방법은 다음과 같습니다.

public void getResults() {
    Stromg rootURL = "localhost:8080/"
    String apiURL = rootURL + "home";

    try {
        String response = new GetTask(MainActivity.this).execute(apiURL).get();

        JSONObject jsonResponse = new JSONObject(response);
        String results = (String) jsonResponse.get("results");

        Toast.makeText(getApplicationContext(), results, Toast.LENGTH_SHORT).show();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

 

getResults() 메소드를 MainActivity의 메소드로 선언하고, 앱 화면에서 특정 동작에 서버에서 데이터를 가져오거나 입력할 때 사용하면 됩니다.

 

GetTask는 "GET" 방식으로 HTTP 통신을 수행하는 클래스로, AsyncTask를 상속받아야 합니다.

(HTTP 등 몇몇 작업은 반드시 비동기로 수행되어야 함)

 

실제 통신은 GetTask 클래스의 doInBackground() 메소드에서 수행됩니다.

 

public class GetTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String apiURL = params[0];

        try {
            URL url = new URL(apiURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 응답 데이터 읽기
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                return response.toString();
            } else {
            	// 오류
                return "[Error] " + responseCode;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "[Error] " + e.getMessage();
        }

    }
}

 

"POST" 방식은 데이터를 Json 형식으로 만들어 전송합니다.

 

public void setField() {
    Stromg rootURL = "localhost:8080/"
    String apiURL = rootURL + "home";

    try {
    	String id = "abc";
    	String jsonData = "{ \"id\": \"" + id + "\" }";
        String response = new PostTask(MainActivity.this).execute(apiURL, jsonData).get();

        JSONObject jsonResponse = new JSONObject(response);
        String results = (String) jsonResponse.get("results");

        Toast.makeText(getApplicationContext(), results, Toast.LENGTH_SHORT).show();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

 

"GET" 방식과 큰 차이는 없고, PostTask 생성 및 실행에서 jsonData를 넘겨줍니다.

PostTask 클래스는 다음과 같습니다.

 

public class PostTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String apiURL = params[0];
        String jsonData = params[1]; // POST로 보낼 데이터

        try {
            URL url = new URL(apiURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json"); // 요청 데이터의 형식에 따라 변경

            // POST 데이터 전송을 위해 OutputStream 사용
            connection.setDoOutput(true);
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(jsonData);
            outputStream.flush();
            outputStream.close();

            // 응답 코드 확인
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                return response.toString();
            } else {
                // 오류
                return "[Error] " + responseCode;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "[Error] " + e.getMessage();
        }

    }

}