开发者

JSON,XML connecting to web api for Android?

I am pretty new to t开发者_如何学Gohe world of Android and Java and I am wondering how I get data from the web api here http://www.imdbapi.com/ Into android. Should I use JSON or XML? What are the steps? Firstly I want to know how to download the data and then how to parse it to variables. Any sample code?


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();
}

As for parsing, here you go: http://developer.android.com/reference/org/json/package-summary.html

btw, this was all easily found on google : )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜