Ackman Ackman - 3 months ago 16
reST (reStructuredText) Question

Synchronous request failing HTTP

I am using okHTTP library to make an http request. It goes through but sometimes, my work in android progresses without complete response arrival. I realize this is happening because of the nature of my request being ASYNC.

OkHttpClient client = new OkHttpClient();
String url = "https://beta-pp-api.polkadoc.com/v1.0/products?category=CP&available_via=mail_order";
{
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", authentication.getToken())
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.addHeader("X-Service-Code", "PP")
.get()
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e){
//do nothing!
}

@Override
public void onResponse(Response response) throws IOException
try {
jsonArray = new JSONArray(response.body().string());
} catch (JSONException e) {
e.printStackTrace();
}


}
});
}


I have tried calling

Response response = client.newCall(request).execute();


However, it fails because in Android we cannot call Sync request on main thread. leads to error NetworkOnMainThread android.os.

Is there a solution to this problem.

Answer

Do the process in a background thread something like below:

OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(15, TimeUnit.SECONDS)
                        .writeTimeout(15, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .build();

new AsyncTask<Void, Void, JSONArray>() {

    @Override
    protected JSONArray doInBackground(Void... voids) {
        Request request = new Request.Builder()
                            .url(url)
                            .addHeader("Authorization", authentication.getToken())
                            .addHeader("Content-Type", "application/json")
                            .addHeader("Accept", "application/json")
                            .addHeader("X-Service-Code", "PP")
                            .get()
                            .build();

        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return new JSONArray(response.body().string());
            } else {
                // notify error
            }
        } catch (IOException e) {
            // notify error e.getMessage()
        }

        return null;
    }

    @Override
    protected void onPostExecute(JSONArray jsonArray) {
        super.onPostExecute(jsonArray);
        if (jsonArray != null && jsonArray.size() > 0) {
            // notify status using LocalBroadcastManager or EventBus
        }
    }
}.execute();