2011-07-06 2 views
0

나는 안드로이드와 자바의 세계에 꽤 새롭다. 그리고 내가 웹 API에서 데이터를 얻는 방법을 궁금하다. http://www.imdbapi.com/ android. JSON 또는 XML을 사용해야합니까? 단계는 무엇입니까? 먼저 데이터를 다운로드하는 방법과 변수를 구문 분석하는 방법을 알고 싶습니다. 샘플 코드는 무엇입니까? 구문 분석에 관해서는JSON, Android 용 웹 API에 XML을 연결 하시겠습니까?

답변

0
HttpClient httpclient = new DefaultHttpClient(); 
    // Prepare a request object 
    HttpGet httpget = new HttpGet(url); 
    // Execute the request 
    HttpResponse response; 

    JSONArray arr = new JSONArray(); 
    try { 
     response = httpclient.execute(httpget); 

     HttpEntity entity = response.getEntity(); 

     if (entity != null && response.getStatusLine().getStatusCode() == 200) { 
       // A Simple JSON Response Read 
       InputStream instream = entity.getContent(); 
       String result = convertStreamToString(instream); 
       arr=new JSONArray(result); 
       instream.close(); 

      } 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      Log.e(TAG,e.toString()); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      Log.e(TAG,e.toString()); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      Log.e(TAG,e.toString()); 
     } 

     return arr; 


public static String convertStreamToString(InputStream is) { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     Log.e(TAG + "ERROR",e.toString()); 

    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      Log.e(TAG + "ERRO",e.toString()); 
     } 
    } 
    return sb.toString(); 
} 

, 여기 당신은 간다 : http://developer.android.com/reference/org/json/package-summary.html

BTW,이 모든 쉽게 구글에서 발견되었다)

+0

가 자바에서 JSON을 구문 분석 너무 쉽게 몰랐 : O –

+0

이 실행 14 sdk 버전? 2.3.3에서 실행하고 싶다면 어떻게해야합니까? 대신 json 대신 이러한 매개 변수를 가져 오는 대체 방법이 있습니까? –

+0

이 코드는 android studio의 TAG에 오류를 발생시킵니다. 'TAG '은'android.support.v4.app.Fragment''에 개인 액세스 권한이 있습니다. – Shivam

관련 문제