NineCattoRules
NineCattoRules

Reputation: 2428

Getting JSON data using OkHttpClient

I started learning Android Studio, and I would like to retrieve some JSON data from a URL page something like this:

This works

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

This code works fine, it gets JSON data from my url.

Instead of this example below doesn't work for me:

This doesn't work

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
    }

}

There are no errors in the code however when I add getData(); for example inside onCreate function, the app stop to work with this error FATAL EXCEPTION: main

Why I'm unable to retrieve the JSON data using OkHttpClient?

Upvotes: 0

Views: 1087

Answers (1)

ortegaivonne28
ortegaivonne28

Reputation: 41

I think you should try to do something like this:

    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

            }
        }
    });
}

Add this in case you want your url to look like this: http://example.com?query=theQuery&secondQuery=theSecondQuery

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

Upvotes: 1

Related Questions