2013-01-05 2 views
3

내 Android 애플리케이션에는 EditText, 하나는 Button, 하나는 Listview입니다. EditText 필드에 영화 이름을 입력하고 Button을 누르면 ListViewEditText 입력란과 일치하는 Rotten Tomatoes 웹 사이트의 영화 이름이 채워지 길 원합니다.Rotten Tomatoes에서 JSON API를 사용하여 영화 데이터를 요청하는 방법은 무엇입니까?

그러나 동영상 데이터를 가져 오는 데 Rotten Tomatoes JSON API을 사용하는 방법을 알 수 없습니다. 어떻게해야합니까?

답변

13

기본적으로, 당신이 필요합니다 네 가지를 수행합니다

  1. 당신이 here을 할 수있는 안드로이드 응용 프로그램에 대한 썩은 토마토 API 키를 가져옵니다. 이 키는 앱에 대한 서비스를 식별하고 인증 된 액세스 권한을 부여합니다. API에 요청할 때마다 사용해야합니다. 그게 다야, 아무것도 복잡하지 않아.
  2. HTTP 요청을 API 웹 서버에 보냅니다. 요청 URL은 가져 오려는 데이터에 따라 다릅니다. 예를 들어, 영화 목록을 얻으려면 URL은 http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=[your_api_key]&q=[search_keyword]&page_limit=[page_limit]입니다 (this 페이지 참조).
  3. 웹 서버에서 응답을 읽습니다. 방금 연결 한 마지막 페이지에서 볼 수 있듯이 응답은 JSON 개체가 될 것입니다. Rotten Tomatoes가 API에 사용하기로 한 데이터 형식이기 때문입니다.
  4. JSON 개체의 원하는 값 (예 : 영화 제목)을 가져 와서 그에 따라 앱 UI를 업데이트하십시오.

나는이 작업을 수행 할 작은 데모 응용 프로그램을 만들었습니다. 아래 코드를 사용해보십시오.

MainActivity.java

import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ListView; 

import org.apache.http.HttpResponse; 
import org.apache.http.HttpStatus; 
import org.apache.http.StatusLine; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.ByteArrayOutputStream; 
import java.io.IOException; 

public class MainActivity extends Activity 
{ 
    // the Rotten Tomatoes API key of your application! get this from their website 
    private static final String API_KEY = <your api key!>; 

    // the number of movies you want to get in a single request to their web server 
    private static final int MOVIE_PAGE_LIMIT = 10; 

    private EditText searchBox; 
    private Button searchButton; 
    private ListView moviesList; 

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

     searchBox = (EditText) findViewById(R.id.text_search_box); 
     searchButton = (Button) findViewById(R.id.button_search); 
     searchButton.setOnClickListener(new OnClickListener() 
     { 
      // send an API request when the button is pressed 
      @Override 
      public void onClick(View arg0) 
      { 
       new RequestTask().execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=" + API_KEY + "&q=" + searchBox.getText().toString().trim() + "&page_limit=" + MOVIE_PAGE_LIMIT); 
      } 
     }); 
     moviesList = (ListView) findViewById(R.id.list_movies); 
    } 

    private void refreshMoviesList(String[] movieTitles) 
    { 
     moviesList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, movieTitles)); 
    } 

    private class RequestTask extends AsyncTask<String, String, String> 
    { 
     // make a request to the specified url 
     @Override 
     protected String doInBackground(String... uri) 
     { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpResponse response; 
      String responseString = null; 
      try 
      { 
       // make a HTTP request 
       response = httpclient.execute(new HttpGet(uri[0])); 
       StatusLine statusLine = response.getStatusLine(); 
       if (statusLine.getStatusCode() == HttpStatus.SC_OK) 
       { 
        // request successful - read the response and close the connection 
        ByteArrayOutputStream out = new ByteArrayOutputStream(); 
        response.getEntity().writeTo(out); 
        out.close(); 
        responseString = out.toString(); 
       } 
       else 
       { 
        // request failed - close the connection 
        response.getEntity().getContent().close(); 
        throw new IOException(statusLine.getReasonPhrase()); 
       } 
      } 
      catch (Exception e) 
      { 
       Log.d("Test", "Couldn't make a successful request!"); 
      } 
      return responseString; 
     } 

     // if the request above completed successfully, this method will 
     // automatically run so you can do something with the response 
     @Override 
     protected void onPostExecute(String response) 
     { 
      super.onPostExecute(response); 

      if (response != null) 
      { 
       try 
       { 
        // convert the String response to a JSON object, 
        // because JSON is the response format Rotten Tomatoes uses 
        JSONObject jsonResponse = new JSONObject(response); 

        // fetch the array of movies in the response 
        JSONArray movies = jsonResponse.getJSONArray("movies"); 

        // add each movie's title to an array 
        String[] movieTitles = new String[movies.length()]; 
        for (int i = 0; i < movies.length(); i++) 
        { 
         JSONObject movie = movies.getJSONObject(i); 
         movieTitles[i] = movie.getString("title"); 
        } 

        // update the UI 
        refreshMoviesList(movieTitles); 
       } 
       catch (JSONException e) 
       { 
        Log.d("Test", "Failed to parse the JSON response!"); 
       } 
      } 
     } 
    } 
} 

입술/레이아웃/activity_main한다.XML

<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" > 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="#E9E9E9" 
     android:focusable="true" 
     android:focusableInTouchMode="true" 
     android:orientation="horizontal" 
     android:padding="3dip" > 

     <EditText 
      android:id="@+id/text_search_box" 
      android:layout_width="0dip" 
      android:layout_height="wrap_content" 
      android:layout_weight="1.0" 
      android:gravity="center" /> 

     <Button 
      android:id="@+id/button_search" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:drawableRight="@android:drawable/ic_search_category_default" /> 
    </LinearLayout> 

    <ListView 
     android:id="@+id/list_movies" 
     android:layout_width="match_parent" 
     android:layout_height="0dip" 
     android:layout_weight="1.0" /> 

</LinearLayout> 

그리고 AndroidManifest.xml (이것은 당신은 분명 썩은 토마토 '웹 서버로 요청을 만들 필요가 인터넷을 사용하는 안드로이드 응용 프로그램 권한, 부여) 당신이 줄을 추가 :

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

보너스 대답 :

당신이 검색 애를 입력하면 "라이브"검색 결과를 원하는 경우 yword를 EditText 필드에 추가하고 EditText의 addTextChangedListener() 메서드를 통해 TextWatcher를 추가 한 다음 onTextChanged()의 HTTP 요청을 수행합니다.

+0

와우 나는 그것을 믿을 수 없다. 포스트는 나에게 너무 많은 도움을 주며, 매우 자세하고 읽기 쉽다. 지금 코드를 테스트하고 어떻게 진행되는지 알려줄 것이지만, 무엇보다도 먼저 말해야한다. 이걸로 큰 감사! – user1924895

+0

나는 코드를 테스트했는데, 매력처럼 작동한다. 시간을 낭비하고 며칠을 다 써 버리며, 너는 내게 큰 시간을 절약 해 주었다. 당신이 좋아하는 사람, 그 stackoverflow가 너무 성공적이기 때문에 당신이 쏟은 노력은 아주 훌륭합니다. 감사합니다. 나는 저항 할 수는 없지만 물어볼 수있는 기회가 있습니까? 나는 당신을 이메일로 보내거나 미래에 연락 할 수있는 기회가 있습니까? 인터넷에있는 모든 장소에서 나는 당신이했던 방식대로 도움이되지 못했습니다. 당신 같은 자부심 같은 사람과 연락하는 방법이 없다면 수치 스러울 것입니다. – user1924895

+0

죄송합니다, 현재 익명 성을 유지하고 싶습니다. :) 건배. –

0

이런 종류의 문제에 대한 일반적인 접근 방식은 다음과 같습니다 나쁜입니다 긴 주 (또는 UI) 스레드에서 작업을 실행하기 때문에

가 귀하의 요청 및 응답의 네트워킹 및 구문 분석을 처리하는 AsyncTask 만들기 생각. AsyncTask에서 HttpClient를 사용하여 API 서버와 통신하고 JSON 파서 라이브러리 (예 : Google's gson)를 사용하여 JSON 요청/응답을 구문 분석합니다.

당신은 HttpClient를을 사용하여 원격 서버와 통신하는 방법에 대한 자습서 많이 찾을 수 있습니다, 여기에 (이 품질의를 위해 내가 보증 할 수 없습니다) 그 중 하나입니다

http://www.mysamplecode.com/2011/09/android-asynctask-httpclient-with.html

관련 문제