본문 바로가기
안드로이드

[Android] REST API 통신하기

by 코딩히어로 2022. 9. 16.
728x90

1


REST API 통신은 기본적으로 Http를 사용하기 때문에 기존에 사용하던

Http 클래스를 이용해서 간단하게 구현이 가능했습니다

package com.example.sw_system;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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

    private configs conf;

    @Override
    protected String doInBackground(String... strings) {
        String Result = "Error";

        conf = new configs();

        try {
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();

            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            conn.setUseCaches(false);

            if(url_state!=0) {
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Accept", "application/json");
                if(url_state!=1) {
                    conn.setRequestProperty("Authorization", "Bearer " + token);
                }
            }

            conn.setRequestMethod("POST");

            String body = strings[0];

            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
            osw.write(body);
            osw.flush();

            InputStreamReader tmp = new InputStreamReader(conn.getInputStream(),"UTF-8");
            BufferedReader reader = new BufferedReader(tmp);
            StringBuilder builder = new StringBuilder();
            String str;

            while((str=reader.readLine())!=null){
                builder.append(str);
            }
            Result = builder.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result;
    }
}

위 코드는 Http 통신을 할 때 사용되던 소스로 일반적인 POST 방식의 Http 통신에서 사용됩니다

하지만 위 코드를 가지고 REST API에 접근하면 InputStreamReader에서 에러가 발생합니다

 

그 이유는 너무나도 간단한데 REST API를 사용하기 위해서는 가장 기본적으로

Content-Type과 Accept를 설정해주어야 하기 때문입니다

REST API는 Content-Type,Accept 둘 다 json 형식을 사용하기 때문에

이 부분이 명시되지 않을 경우 서버상 REST API에서 걸러지게 되므로 not found 에러가 발생합니다.

 

그럼 위 코드에서 단 두줄만 추가하게 되면 REST API를 사용할 수 있습니다

package com.example.sw_system;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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

    private configs conf;

    @Override
    protected String doInBackground(String... strings) {
        String Result = "Error";

        conf = new configs();

        try {
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();

            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            conn.setUseCaches(false);
            
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");

            if(url_state!=0) {
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Accept", "application/json");
                if(url_state!=1) {
                    conn.setRequestProperty("Authorization", "Bearer " + token);
                }
            }

            conn.setRequestMethod("POST");

            String body = strings[0];

            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
            osw.write(body);
            osw.flush();

            InputStreamReader tmp = new InputStreamReader(conn.getInputStream(),"UTF-8");
            BufferedReader reader = new BufferedReader(tmp);
            StringBuilder builder = new StringBuilder();
            String str;

            while((str=reader.readLine())!=null){
                builder.append(str);
            }
            Result = builder.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result;
    }
}

HttpURLConnection 객체에 setRequestProperty 함수를 통해서

application/json 타입으로 지정해주는 코드를 두줄만 추가하면 REST API 사용할 준비가 되었습니다

728x90
반응형

댓글