使用YouTube Data API v3获取YouTube标题/观看次数/缩略图

时间:2016-04-29 07:05:47

标签: android android-youtube-api youtube-data-api

我是Android中整个YouTube Data API v3的新用户。到目前为止,我正在使用AsyncTask HttpURLConnectionBufferedReader从API构建字符串响应,然后将其解析为JSON Object。我已经读过有一个我可以使用的库而不是这个,但我没有找到使用它的android示例。

到目前为止,这是我的代码:

    public class TestAsyncTask extends AsyncTask<Void, Void, String> {
    private Context mContext;
    private String mUrl;

    public TestAsyncTask(Context context, String url) {
        mContext = context;
        mUrl = url;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        test = findViewById(R.id.test).toString();
    }

    @Override
    protected String doInBackground(Void... params) {
        String resultString = null;
        resultString = getJSON(mUrl);

        return resultString;
    }

    @Override
    protected void onPostExecute(String strings) {
        super.onPostExecute(strings);
        test = strings;
        parseJSON(test);


    }

    private String getJSON(String url) {
        HttpURLConnection c = null;
        try {
            URL u = new URL(url);
            c = (HttpURLConnection) u.openConnection();
            c.connect();
            int status = c.getResponseCode();
            switch (status) {
                case 200:
                case 201:
                    BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line+"\n");
                    }
                    br.close();
                    return sb.toString();
            }

        } catch (Exception ex) {
            return ex.toString();
        } finally {
            if (c != null) {
                try {
                    c.disconnect();
                } catch (Exception ex) {
                    //disconnect error
                }
            }
        }
        return null;
    }

    private void parseJSON (String jsonStr){

        TextView testview = (TextView) findViewById(R.id.test);
        try {
            JSONObject obj = new JSONObject(jsonStr);
            MainActivity.object = obj;

        }

        catch (JSONException ex){

            testview.setText("Błąd" + ex.toString());

        }



    }

0 个答案:

没有答案