Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Jeremiah Shore
Jeremiah Shore
31,168 Points

How can I fix an issue where multiple okhttp requests fail over a mobile network?

I am working on an app that pulls information from an API via JSON format. This one request has never been problematic: When the app loads it runs one request that pulls information to create an array of objects that have a name, category, and "UrlName". The url name is used to run additional requests to fetch more information about each object.

Once the initial data is loaded, subsequent requests are run—one for each object in the existing array. This is what is causing problems. There is no delay between each request, they are run in rapid succession.

This series of subsequent requests works absolutely fine on a wifi network; it has never given me a response other than 200 (ok). When I try to run anywhere from 10 or more requests on a cellular network, that is when it seems to reliably fail, but the number of successful requests varies each time. I am getting response code 403 (forbidden) back from the service.

Since the requests process fine on a wifi network, I was thinking it could perhaps be something on the cellular carrier's data network that is blocking or denying my requests in some way. Is it possible that I get a 403 code because it thinks I am running a DoS attack or something?

**One idea I have to possibly fix this is to wait a few seconds in between each request, which I will likely try in the mean time while waiting for an answer.

2 Answers

Mateo Cuervo
Mateo Cuervo
2,511 Points

hey Jeremiah did you figured out how to make multirequest using okhttp? I would appreciate the code snippet

Jeremiah Shore
Jeremiah Shore
31,168 Points

Mateo Cuervo,

I have not worked on this code any further, so unfortunately I do not have it available for reference. If I do I will try to remember to post here. Thanks for looking to answer though.

Mateo Cuervo
Mateo Cuervo
2,511 Points

Hi Jeremiah,

I got it working for 2 different request with AsyncTask no idea how it performs for pagination but leaving code in here might help someone else, full code at: https://github.com/cooervo/the-movie-DB-android-app/blob/master/app/src/main/java/com/cooervo/filmography/controllers/http/AsyncDownloader.java

The snippet:

**
 * Public class to be re used for downloading JSON response using library
 * OkHttp.
 *
 * We extend AsyncTask because so we can make an Asynchronous call to retrieve the
 * response from theMovieDB.org API without affecting the GUI.
 *
 * Also this class is reused in the application to reduce boiler plate code. If needed we can subclass
 * this class and override method onPostExecute() which can be used to do specific things in the
 * main thread (GUI).
 */
public class AsyncDownloader extends AsyncTask<String, Integer, String> {

    public static final String TAG = AsyncDownloader.class.getSimpleName();

    private Context context;
    private Class classToLoad;
    private ProgressDialog dialog;

    private String url;

    public AsyncDownloader(Context ctx, Class c) {
        context = ctx;
        classToLoad = c;
    }

    /**
     * onPreExecute runs on the UI thread before doInBackground.
     * This will start showing a small dialog that says Loading with a spinner
     * to let the user know download is in progress
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        dialog = new ProgressDialog(context);
        dialog.setMessage("Loading...");
        dialog.setProgressStyle(dialog.STYLE_SPINNER);
        dialog.setCancelable(false);
        dialog.show();
    }

    /**
     * doInBackground() runs in the background on a worker thread. This is where code that can block the GUI should go.
     *  Since we are using asynctask this is already in background threas we use okHttp method
     *  call.execute() which executes in current thread (which is the background threas of this Async class)
     *  Once we finish retrieving jsonData it is passed to method onPostExecute()
     * @param params
     * @return
     */
    @Override
    protected String doInBackground(String... params) {

        String url = params[0];

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);

        Response response = null;

        String jsonData = null;

        try {
            response = call.execute();

            if (response.isSuccessful()) {
                jsonData = response.body().string();

            } else {
                jsonData = null;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonData; //This is returned to onPostExecute()
    }

    /**
     * onPostExecute runs on the  main (GUI) thread and receives
     * the result of doInBackground.
     *
     * Here we pass a string representation of jsonData to the child/receiver
     * activity.
     *
     * @param jsonData
     */
    @Override
    protected void onPostExecute(String jsonData) {
        super.onPostExecute(jsonData);
        dialog.dismiss();

        Intent i = new Intent(context, classToLoad);
        i.putExtra("jsonData", jsonData);
        context.startActivity(i);
    }
}