반응형

이번 포스팅에서는 안드로이드앱에서 REST 요청을 하는 방법을 다룹니다.


웹브라우저의 주소창에 REST 요청 주소를 입력하여 JSON 응답을 받았던 것처럼 동작하는 앱을 구현해보도록 하겠습니다.



  • Flickr API 사용 해보기

http://webnautes.tistory.com/459


  • Android에서 REST 요청 후 JSON 응답 받기

http://webnautes.tistory.com/462


  • Android에서 JSON 파싱하여 ListView에 출력

http://webnautes.tistory.com/471


  • ListView 아이템 클릭하면 이미지 다운로드해서 보여주기

http://webnautes.tistory.com/472



최초 작성        - 2014.06.30

최종 업데이트 - 2017.12.21




UI 디자인은 다음처럼 간단합니다.

요청을 하기 위한 버튼과 결과 텍스트를 뿌려줄 TextView로 구성됩니다.




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context="com.tistory.webnautes.imagesearchexample.MainActivity">

   <TextView
       android:layout_width="match_parent"
       android:layout_height="0dp"
       android:layout_weight="0.9"
       android:layout_margin="15dp"
       android:padding="15dp"
       android:maxLines="100"
       android:id="@+id/textview_main_jsontext"
       android:singleLine="false"
       android:scrollbars="vertical"
       android:scrollHorizontally="false"
       android:text="" />

   <Button
       android:layout_width="match_parent"
       android:layout_height="0dp"
       android:layout_weight="0.1"
       android:layout_margin="15dp"
       android:text="JSON 가져오기"
       android:id="@+id/button_main_requestjson"/>


</LinearLayout>






"JSON 가져오기 " 버튼을 누르면 REST 요청이 이루어지며 잠시 후 TextView에 JSON 텍스트를 뿌려줍니다.

위아래로 스크롤 해가며 내용을 확인해 볼 수 있습니다.





인터넷 연결을 해야하므로 퍼미션을 추가해야 합니다. AndroidManifest.xml에 다음 한 줄을 추가해줍니다.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.tistory.webnautes.imagesearchexample">

   <uses-permission android:name="android.permission.INTERNET" />

   <application




필요한 변수들입니다. 웹브라우저에서 사용했던 REST 요청 URL을 거의 그대로 사용합니다.

API_KEY 부분은 발급받은 API 키로 변경하세요


   private static final String TAG = "imagesearchexample";
   public static final int LOAD_SUCCESS = 101;

   private String SEARCH_URL = "https://secure.flickr.com/services/rest/?method=flickr.photos.search";
   private String API_KEY = "&api_key=API_KEY";
   private String PER_PAGE = "&per_page=50";
   private String SORT = "&sort=interestingness-desc";
   private String FORMAT = "&format=json";
   private String CONTECT_TYPE = "&content_type=1";
   private String SEARCH_TEXT = "&text='cat'";
   private String REQUEST_URL = SEARCH_URL + API_KEY + PER_PAGE + SORT + FORMAT + CONTECT_TYPE + SEARCH_TEXT;

   private ProgressDialog progressDialog;
   private TextView textviewJSONText;





버튼을 누르면 progressDialog를 화면에 보여주고 나서 getJSON() 메소드를 호출합니다.


   @Override
   protected void onCreate(Bundle savedInstanceState) {

        . . . . . . . . . . . . . . . . . . . . . . . . . . . .


       buttonRequestJSON.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {

               progressDialog = new ProgressDialog( MainActivity.this );
               progressDialog.setMessage("Please wait.....");
               progressDialog.show();

               getJSON();
           }
       });
   }





쓰레드를 실행하여 REQUEST_URL로 REST 요청을 합니다.


 public void  getJSON() {

       Thread thread = new Thread(new Runnable() {

           public void run() {

               String result;

               try {

                   Log.d(TAG, REQUEST_URL);
                   URL url = new URL(REQUEST_URL);
                   HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();


                   httpURLConnection.setReadTimeout(3000);
                   httpURLConnection.setConnectTimeout(3000);
                   httpURLConnection.setDoOutput(true);
                   httpURLConnection.setDoInput(true);
                   httpURLConnection.setRequestMethod("GET");
                   httpURLConnection.setUseCaches(false);
                   httpURLConnection.connect();

                   . . . . . . . . . . . . . . . . . . .

       });
       thread.start();
   }




JSON 응답을 저장합니다.

  public void  getJSON() {

       Thread thread = new Thread(new Runnable() {

           public void run() {

                    . . . . . . . . . . . . . . . . . . . . .

                   InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                   BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                   StringBuilder sb = new StringBuilder();
                   String line;


                   while ((line = bufferedReader.readLine()) != null) {
                       sb.append(line);
                   }

                   bufferedReader.close();
                   httpURLConnection.disconnect();

                   result = sb.toString().trim();

                   . . . . . . . . . . . . . . . . . . . .
           }

       });
       thread.start();
   }




결과를 TextView에 보여주는 UI 처리를 하기 위해서 핸들러를 실행합니다.


  public void  getJSON() {

       Thread thread = new Thread(new Runnable() {

           public void run() {

               . . . . . . . . . . . . . . . . . . . . . . . . . .


               Message message = mHandler.obtainMessage(LOAD_SUCCESS, result);
               mHandler.sendMessage(message);
           }

       });
       thread.start();
   }




progressDialog를 제거하고 JSON 응답을 TextView에 출력합니다.


   private final MyHandler mHandler = new MyHandler(this);


   private static class MyHandler extends Handler {
       private final WeakReference<MainActivity> weakReference;

       public MyHandler(MainActivity mainactivity) {
           weakReference = new WeakReference<MainActivity>(mainactivity);
       }

       @Override
       public void handleMessage(Message msg) {

           MainActivity mainactivity = weakReference.get();

           if (mainactivity != null) {
               switch (msg.what) {

                   case LOAD_SUCCESS:
                       mainactivity.progressDialog.dismiss();

                       String jsonString = (String)msg.obj;

                       mainactivity.textviewJSONText.setText(jsonString);
                       break;
               }
           }
       }
   }





전체 소스코드입니다.


package com.tistory.webnautes.imagesearchexample;

import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

   private static final String TAG = "imagesearchexample";
   public static final int LOAD_SUCCESS = 101;

   private String SEARCH_URL = "https://secure.flickr.com/services/rest/?method=flickr.photos.search";
   private String API_KEY = "&api_key=b901381d5d56065a36032436ff20243a";
   private String PER_PAGE = "&per_page=50";
   private String SORT = "&sort=interestingness-desc";
   private String FORMAT = "&format=json";
   private String CONTECT_TYPE = "&content_type=1";
   private String SEARCH_TEXT = "&text='cat'";
   private String REQUEST_URL = SEARCH_URL + API_KEY + PER_PAGE + SORT + FORMAT + CONTECT_TYPE + SEARCH_TEXT;

   private ProgressDialog progressDialog;
   private TextView textviewJSONText;


   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       Button buttonRequestJSON = (Button)findViewById(R.id.button_main_requestjson);
       textviewJSONText = (TextView)findViewById(R.id.textview_main_jsontext);
       textviewJSONText.setMovementMethod(new ScrollingMovementMethod());

       buttonRequestJSON.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {

               progressDialog = new ProgressDialog( MainActivity.this );
               progressDialog.setMessage("Please wait.....");
               progressDialog.show();

               getJSON();
           }
       });
   }



   private final MyHandler mHandler = new MyHandler(this);


   private static class MyHandler extends Handler {
       private final WeakReference<MainActivity> weakReference;

       public MyHandler(MainActivity mainactivity) {
           weakReference = new WeakReference<MainActivity>(mainactivity);
       }

       @Override
       public void handleMessage(Message msg) {

           MainActivity mainactivity = weakReference.get();

           if (mainactivity != null) {
               switch (msg.what) {

                   case LOAD_SUCCESS:
                       mainactivity.progressDialog.dismiss();

                       String jsonString = (String)msg.obj;

                       mainactivity.textviewJSONText.setText(jsonString);
                       break;
               }
           }
       }
   }




   public void  getJSON() {

       Thread thread = new Thread(new Runnable() {

           public void run() {

               String result;

               try {

                   Log.d(TAG, REQUEST_URL);
                   URL url = new URL(REQUEST_URL);
                   HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();


                   httpURLConnection.setReadTimeout(3000);
                   httpURLConnection.setConnectTimeout(3000);
                   httpURLConnection.setDoOutput(true);
                   httpURLConnection.setDoInput(true);
                   httpURLConnection.setRequestMethod("GET");
                   httpURLConnection.setUseCaches(false);
                   httpURLConnection.connect();


                   int responseStatusCode = httpURLConnection.getResponseCode();

                   InputStream inputStream;
                   if (responseStatusCode == HttpURLConnection.HTTP_OK) {

                       inputStream = httpURLConnection.getInputStream();
                   } else {
                       inputStream = httpURLConnection.getErrorStream();

                   }


                   InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                   BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                   StringBuilder sb = new StringBuilder();
                   String line;


                   while ((line = bufferedReader.readLine()) != null) {
                       sb.append(line);
                   }

                   bufferedReader.close();
                   httpURLConnection.disconnect();

                   result = sb.toString().trim();


               } catch (Exception e) {
                   result = e.toString();
               }


               Message message = mHandler.obtainMessage(LOAD_SUCCESS, result);
               mHandler.sendMessage(message);
           }

       });
       thread.start();
   }

}



반응형

포스트 작성시에는 문제 없었지만 이후 문제가 생길 수 있습니다.
댓글로 알려주시면 빠른 시일내에 답변을 드리겠습니다.

여러분의 응원으로 좋은 컨텐츠가 만들어집니다.
지금 본 내용이 도움이 되었다면 유튜브 구독 부탁드립니다. 감사합니다 : )

유튜브 구독하기


제가 쓴 책도 한번 검토해보세요.

  1. dosona 2018.01.11 12:20

    혹시 다음 블로그 검색 api쓰는것도 동일한가여?

    • Favicon of https://webnautes.tistory.com BlogIcon webnautes 2018.01.11 12:28 신고

      요청 URL 포맷과 응답 포맷만 다를 뿐 하는 방법은 동일할 듯합니다.

  2. dosona 2018.01.11 15:54

    다음 블로그 api는 헤더 부분에 app key를 작성하게되는데 어떻게해야할지 모르겠군요 어느것부터 공부해야할까여?

    • Favicon of https://webnautes.tistory.com BlogIcon webnautes 2018.01.11 18:45 신고

      찾아보니 다음 사이트로 통합되었네요.

      우선 문서를 찾아서 읽어보세요..

      https://developers.kakao.com

+ Recent posts