使用OkHttpClient获取JSON数据

时间:2017-06-09 16:25:55

标签: android okhttp

我开始学习Android Studio,我想从URL页面中检索一些JSON数据:

此作品

private void getData() {
    AsyncHttpClient client = new AsyncHttpClient();
    API_Util.Https_code(client);

    client.get("https://example.com/api.php", new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            Explore_model_item model;
            try {
                JSONArray array = response.getJSONArray("items");
                for (int i = 0; i < array.length(); i++) {
                    model = new Explore_model_item();

                    JSONObject obj = array.getJSONObject(i);
                    model.id = obj.getString("id");
                    model.title = obj.getString("title");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (pDialog.getVisibility() == View.VISIBLE) {
                pDialog.setVisibility(View.INVISIBLE);
                listview_items.setVisibility(View.VISIBLE);
                if (getResources().getBoolean(R.bool.Ads_check)==true)
                {
                    initListViewItems();
                }else {
                    listview_items.setAdapter(list_Adapter);
                }
            } else {
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
            super.onSuccess(statusCode, headers, response);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            super.onFailure(statusCode, headers, throwable, errorResponse);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
            super.onFailure(statusCode, headers, throwable, errorResponse);
        }
    });
}

此代码工作正常,它从我的网址获取JSON数据。

以下代替这个例子并不适用于我:

这不起作用

private void getData() {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url("https://example.com/api.php")
            .build();
    Response responses = null;

    try {
        responses = client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        Explore_model_item model;

    try {
        String jsonData = responses.body().string();
        try {
            JSONObject Jobject = new JSONObject(jsonData);
            JSONArray Jarray = Jobject.getJSONArray("items");
            for (int i = 0; i < Jarray.length(); i++) {
                model = new Explore_model_item();

                JSONObject obj = Jarray.getJSONObject(i);
                model.id = obj.getString("id");
                model.title = obj.getString("title");
            }

        }
        catch (JSONException e) {
            //Do something
        }

    }catch(IOException ex) {
        //Do something witht the exception
    }

}

代码中没有错误,但是当我在getData();函数中添加onCreate时,应用停止使用此错误FATAL EXCEPTION: main

为什么我无法使用OkHttpClient检索JSON数据?

1 个答案:

答案 0 :(得分:0)

我认为你应该尝试这样做:

    private void getData(String tweet){

    OkHttpClient client = new OkHttpClient();

    final Request request = new Request.Builder()
            .url("https://example.com")
            .post(body)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if(!response.isSuccessful())
            {
                throw new IOException("Unexpected code: +"+ response);
            }
            else
            {
                String responseBody = response.body().string();
                //Take the data from response body

            }
        }
    });
}

的 如果您希望您的网址如下所示,请添加以下内容: http://example.com?query=theQuery&secondQuery=theSecondQuery

        RequestBody body = new FormBody.Builder()
            .add("query",theQuery)
            .add("secondQuery",theSecondQuery)
            .build();