http://webnautes.tistory.com/462?category=587250
이번 포스팅에서는 안드로이드앱에서 REST 요청을 하는 방법을 다룹니다.
웹브라우저의 주소창에 REST 요청 주소를 입력하여 JSON 응답을 받았던 것처럼 동작하는 앱을 구현해보도록 하겠습니다.
http://webnautes.tistory.com/459
http://webnautes.tistory.com/462
http://webnautes.tistory.com/471
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(); }
} |