text 使用AsyncTask和okHttp&JSON解析获取API数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 使用AsyncTask和okHttp&JSON解析获取API数据相关的知识,希望对你有一定的参考价值。

class HttpGetAsync extends AsyncTask < String, Void, List < threads >> {
    @Override
    protected List < threads > doInBackground(String...strings) {

        try {
            String json = getAPIData(strings[0]);
            JSONObject root = new JSONObject(json);
            JSONArray JSONthreads = root.getJSONArray("threads");
            threadList = new ArrayList < > ();

            for (int i = 0; i < JSONthreads.length(); i++) {
                threads allThreads = new threads();
                JSONObject threadJSON;
                threadJSON = JSONthreads.getJSONObject(i);
                allThreads.setUser_id(threadJSON.getString("user_id"));
                allThreads.setThreadName(threadJSON.getString("title"));
                allThreads.setThread_id(threadJSON.getString("id"));
                threadList.add(allThreads);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return threadList;
    }

    @Override
    protected void onPostExecute(List < threads > threadList) {
        super.onPostExecute(threadList);
        customAdapter = new customAdapter(threadList);
        lv.setAdapter(customAdapter);
    }
}

String getAPIData(String url) throws IOException {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
        .url(url)
        .addHeader("Authorization", token)
        .build();
    Response response = client.newCall(request).execute();

    return response.body().string();
}

以上是关于text 使用AsyncTask和okHttp&JSON解析获取API数据的主要内容,如果未能解决你的问题,请参考以下文章

用AsyncTask实现断点续传

当 AsyncTask 完成时返回一个值

OKHTTP GET 和 POST 请求返回空正文消息

Service的使用:断点下载

Android-异步任务-AsyncTask

text 使用OkHttp高效开发调试