This post is part of a series called Android From Scratch. Show 인터넷은 우리 삶의 중요한 한 부분으로서 우리 중 대부분은 새로운 정보에 대한 탐욕적인 욕구를 발달시켜왔습니다. 우리의 주의 지속 시간도 그 어느 때보다도 짧아서 콘텐츠가 정적인 안드로이드 애플리케이션을 개발하는 것은 좋지 않은 생각일 수 있습니다. 대신 사용자가 열 때마다 새로운 내용을 표시할 수 있는 애플리케이션을 만드는 것을 고려해야 합니다. 그렇게 하기가 어려울 수도 있겠지만 REST API를 통해 리소스를 노출하는 웹 사이트가 점점 더 많아지면서 실제로는 그리 어렵지 않게 할 수 있게 됐습니다. (초보자를 위한 HTTP와 REST 안내서를 참고하세요.) 이번 튜토리얼에서는 안드로이드 SDK에서 이용할 수있는 클래스와 메서드를 사용해 원격 웹 서버에 연결하고 REST API를 사용해 상호작용하는 방법을 보여드리겠습니다. 1. 인터넷 접속 활성화REST API를 사용하려면 당연히 인터넷을 이용할 수 있어야 합니다. 하지만 안드로이드 애플리케이션은 <uses-permission android:name="android.permission.INTERNET" />
2. 백그라운드 스레드 생성안드로이드 플랫폼에서는 애플리케이션의 메인 스레드에서 네트워크 작업을 수행하는 것을 허용하지 않습니다. 따라서 모든 네트워킹 코드는 백그라운드 스레드에 속해야 합니다. 그러한 스레드를 만드는 가장 쉬운 방법은 AsyncTask.execute(new Runnable() { @Override public void run() { // All your networking logic // should be here } }); 백그라운드 스레드에서 작업을 실행하는 것에 대해 자세히 알고 싶다면 '안드로이드 처음부터 배우기(Android From Scratch)' 시리즈의
백그라운드 작업에 대한 튜토리얼을 읽어보길 바랍니다. 3. HTTP 연결 생성
다음 코드는 GitHub API의 루트 엔드포인트와의 연결을 설정하는 방법을 보여줍니다. // Create URL URL githubEndpoint = new URL("https://api.github.com/"); // Create connection HttpsURLConnection myConnection = (HttpsURLConnection) githubEndpoint.openConnection(); 참고로
4. 요청 헤더 추가REST API를 제공하는 대부분의 웹 사이트에서는 앱을 고유하게 식별할 수 있기를 원합니다. 그러한 웹 사이트를 돕는 가장 쉬운 방법은 모든 요청에 고유한 요청에 myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.1");
myConnection.setRequestProperty("Accept", "application/vnd.github.v3+json"); myConnection.setRequestProperty("Contact-Me", ""); 5. 응답 읽기모든 요청
헤더를 전달하고 나면 if (myConnection.getResponseCode() == 200) { // Success // Further processing here } else { // Error handling code goes here }
오류가 없는 경우 이제 InputStream responseBody = myConnection.getInputStream(); 요즘 대부분의 REST API는 유효한 JSON 문서 형식의 데이터를 반환합니다. 따라서 InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8"); 6. JSON 응답 파싱안드로이드 SDK에는 JsonReader라는 클래스가 있어서 이 클래스로 JSON
문서를 손쉽게 파싱할 수 있습니다. JsonReader jsonReader = new JsonReader(responseBodyReader); JSON 문서에서 특정 정보를 추출하는 방법은 구조에 따라 다릅니다. 예를 들어, GitHub REST API의 루트 엔드포인트에서 반환된 JSON 문서는 다음과 같습니다. { "current_user_url": "https://api.github.com/user", "current_user_authorizations_html_url": "https://github.com/settings/connections/applications{/client_id}", "authorizations_url": "https://api.github.com/authorizations", "code_search_url": "https://api.github.com/search/code?q=1{&page,per_page,sort,order}", "emails_url": "https://api.github.com/user/emails", "emojis_url": "https://api.github.com/emojis", "events_url": "https://api.github.com/events", "feeds_url": "https://api.github.com/feeds", "followers_url": "https://api.github.com/user/followers", "following_url": "https://api.github.com/user/following{/target}", "gists_url": "https://api.github.com/gists{/gist_id}", "hub_url": "https://api.github.com/hub", "issue_search_url": "https://api.github.com/search/issues?q=1{&page,per_page,sort,order}", "issues_url": "https://api.github.com/issues", "keys_url": "https://api.github.com/user/keys", "notifications_url": "https://api.github.com/notifications", "organization_repositories_url": "https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}", "organization_url": "https://api.github.com/orgs/{org}", "public_gists_url": "https://api.github.com/gists/public", "rate_limit_url": "https://api.github.com/rate_limit", "repository_url": "https://api.github.com/repos/{owner}/{repo}", "repository_search_url": "https://api.github.com/search/repositories?q=1{&page,per_page,sort,order}", "current_user_repositories_url": "https://api.github.com/user/repos{?type,page,per_page,sort}", "starred_url": "https://api.github.com/user/starred{/owner}{/repo}", "starred_gists_url": "https://api.github.com/gists/starred", "team_url": "https://api.github.com/teams", "user_url": "https://api.github.com/users/{user}", "user_organizations_url": "https://api.github.com/user/orgs", "user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}", "user_search_url": "https://api.github.com/search/users?q=1{&page,per_page,sort,order}" } 보다시피 응답은 여러 키가 포함된 하나의 커다란 JSON 객체에 불과합니다. 여기서 organization_url이라는 키의 값을 추출하려면 다음과 같은 코드를 작성해야 합니다. jsonReader.beginObject(); // Start processing the JSON object while (jsonReader.hasNext()) { // Loop through all keys String key = jsonReader.nextName(); // Fetch the next key if (key.equals("organization_url")) { // Check if desired key // Fetch the value as a String String value = jsonReader.nextString(); // Do something with the value // ... break; // Break out of the loop } else { jsonReader.skipValue(); // Skip values of other keys } } 위 코드에서는 JSON 응답을 토큰 스트림으로 처리합니다. 따라서 메모리를 거의 소비하지 않습니다. 하지만 모든 토큰을 하나씩 처리해야 하기 때문에 큰 응답을 처리하는 동안 속도가 느려질 수 있습니다. 필요한 모든 정보를 추출하고 나면 jsonReader.close(); 또한 myConnection.disconnect(); 7. 다양한 HTTP 메서드 사용하기HTTP 기반 REST 인터페이스는 HTTP 메서드를 사용해 자원을 대상으로 수행해야 하는 연산의 유형을 결정합니다. 이전 단계에서는 HTTP
URL httpbinEndpoint = new URL("https://httpbin.org/post"); HttpsURLConnection myConnection = (HttpsURLConnection) httpbinEndpoint.openConnection(); myConnection.setRequestMethod("POST"); 이미 알고 계실 수도 있겠지만 다음 코드는 간단한 키-값 쌍을 서버에 보내는 방법을 보여줍니다. // Create the data String myData = "message=Hello"; // Enable writing myConnection.setDoOutput(true); // Write the data myConnection.getOutputStream().write(myData.getBytes()); 8. 응답 캐싱하기HTTP 응답을 캐싱하는 것은 언제나 좋은 생각입니다. 그렇게 함으로써 앱의 대역폭 소비를 줄일 수 있을뿐더러 응답 속도도 향상시킬 수 있습니다. API 레벨 13부터 안드로이드 SDK에서는 애플리케이션에 캐시를
설치하려면 다음 코드는 크기가 100,000바이트인 캐시를 설치합니다. HttpResponseCache myCache = HttpResponseCache.install( getCacheDir(), 100000L); 캐시가 설치되면 if (myCache.getHitCount() > 0) { // The cache is working } 결론안드로이드 앱에서 자유롭게 사용할 수 있는 REST API는 수천 개에 달합니다. 이러한 REST API를 이용하면 앱을 더욱 유익하고, 흥미롭고, 기능이 풍부하게 만들 수 있습니다. 이번 튜토리얼에서는
안드로이드 플랫폼의 네트워킹에 대한 자세한 내용은 안드로이드 네트워크 작업 가이드를 참고합니다. |