본문 바로가기
안드로이드

[Android] REST API GET 통신하기

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

1


오늘은 REST API를 통해 HTTP GET 통신하는 방법에 대해 알아보겠습니다

이전 포스팅에서 HTTP POST를 이용해서 REST API와 통신하는 소스를 포스팅했었습니다

POST 방식으로 통신하는 게 궁금하신 분은 다음 포스팅 참고 부탁드립니다

2022.09.16 - [안드로이드] - [Android] REST API 통신하기

 

[Android] REST API 통신하기

REST API 통신은 기본적으로 Http를 사용하기 때문에 기존에 사용하던 Http 클래스를 이용해서 간단하게 구현이 가능했습니다 package com.example.sw_system; import android.os.AsyncTask; import android.util..

codinghero.tistory.com

 

GET 방식으로 통신하는 건 HttpURLConnection의 setRequestMethod 부분을 POST에서

GET으로 변경하기만 하면 될 줄 알았는데 또 한 가지 설정해주어야 되는 부분이 있습니다

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("GET");

            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;
    }
}

위 방식은 이전에 구현한 POST방식에서 RequestMethod만

GET으로 변경했는데 동작시 Http 에러가 발생합니다

 

그 이유는 GET 방식은 OutPutStreamWriter를 열면 안 되기 때문인데

먼저 위 코드에서 OutputStream과 관련된 부분을 지워줍니다

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("GET");

            //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;
    }
}

다음으로 setDoInput과 setDoOutput을 설정해 주어야 합니다

setDoOutput 자체가 post로 데이터를 내보내겠다는 의미이기 때문에 반드시 false로 설정해 주셔야 합니다

그렇지 않으면 RequestMethod를 GET으로 설정했다 하더라도 받는 서버 입장에서는

POST로 데이터가 수신되게 됩니다

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("GET");
            conn.setDoInput(true);
            conn.setDoOutput(false);

            //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;
    }
}

여기까지 하고 명령을 전송하면 GET을 통한 REST API 접근이 가능합니다

728x90
반응형

댓글