【问题标题】:JSON,XML connecting to web api for Android?JSON,XML连接到Android的Web api?
【发布时间】:2011-07-06 16:59:49
【问题描述】:

我对 Android 和 Java 的世界还很陌生,我想知道如何从这里的 web api http://www.imdbapi.com/ 获取数据到 android。 我应该使用 JSON 还是 XML? 步骤是什么?首先我想知道如何下载数据,然后如何将其解析为变量。 有示例代码吗?

【问题讨论】:

    标签: java android xml json


    【解决方案1】:
    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

    顺便说一句,这在谷歌上很容易找到:)

    【讨论】:

    • 这在 14 sdk 版本中运行?如果想在 2.3.3 上运行,我该怎么办?而不是 json 获取这些参数的替代方法是什么?
    • 此代码在 android studio 中的 TAG 处引发错误。 'TAG' has private access in 'android.support.v4.app.Fragment'
    • 您可以删除 TAG ...我将其放入日志中,以便确切知道异常来自何处。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    相关资源
    最近更新 更多