Sending multiple requests using OkHTTP android

alan samuel :

I am sending multiple images using OkHTTP. Since all the requests are asynchronous, I cannot run my final call until the all the requests are done. How can I achieve this in OkHTTP?

I need to run my RunFinalRequest() after all the images have been sent. What I tried is, I put the my RunFinalRequest() on OnResponse() but it sometimes doesnt go through even though there is a response. Is there a better way to do it?

Here is my code.

public void SendALL(){

    OkHttpClient client = new OkHttpClient();
    client.dispatcher().setMaxRequestsPerHost(50);


    final MediaType MEDIA_TYPE = MediaType.parse("image/png");


    for (int i = 0; i < images.size(); i++){


        File sourceFile = new File(images.get(i).getImageURI());


        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)

                .addFormDataPart("image", sourceFile.getName(), RequestBody.create(MEDIA_TYPE, sourceFile))
                .addFormDataPart("name", images.get(i).getJobID())
                .build();

        Request request = new Request.Builder()
                .url("xxxxxxxxxxx")
                .post(requestBody)
                .build();

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

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
    }

    if(signatures.size() > 0){

        File sourceFile = new File(Uri.parse(signatures.get(0).getImageURI()).toString());


        String newJobID = signatures.get(0).getJobID().concat("-signature");


        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)

                .addFormDataPart("image", sourceFile.getName(), RequestBody.create(MEDIA_TYPE, sourceFile))
                .addFormDataPart("name", newJobID)
                .build();

        Request request = new Request.Builder()
                .url("XXXXXXXXXXX")
                .post(requestBody)
                .build();

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

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });

    }

RunFinalRequest();
Mehmed :

You may try following mechanism:

private int uploadedImageCount;

...

public void sendAll() {
    uploadedImageCount = 0;
    OkHttpClient client = new OkHttpClient();
    client.dispatcher().setMaxRequestsPerHost(50);
    MediaType MEDIA_TYPE = MediaType.parse("image/png");

    for (int i = 0; i < images.size(); i++) {
        File sourceFile = new File(images.get(i).getImageURI());

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", sourceFile.getName(), RequestBody.create(MEDIA_TYPE, sourceFile))
                .addFormDataPart("name", images.get(i).getJobID())
                .build();

        Request request = new Request.Builder()
                .url("xxxxxxxxxxx")
                .post(requestBody)
                .build();

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

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    onImageUploaded();
                } else {
                    onImageUploadFailed();
                }
            }
        });
    }

    if (signatures.size() > 0) {
        File sourceFile = new File(Uri.parse(signatures.get(0).getImageURI()).toString());
        String newJobID = signatures.get(0).getJobID().concat("-signature");

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", sourceFile.getName(), RequestBody.create(MEDIA_TYPE, sourceFile))
                .addFormDataPart("name", newJobID)
                .build();

        Request request = new Request.Builder()
                .url("XXXXXXXXXXX")
                .post(requestBody)
                .build();

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

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
    }
}

public void onImageUploaded() {
    uploadedImageCount++;
    if (uploadedImageCount == images.size()) {
        runFinalRequest();
    }
}

public void onImageUploadFailed() {
    // Handle failure case. You may detect failed image and try to resend
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

A query on sending multiple requests using Axios - React

Sending multiple requests using spreadsheets.batchUpdate result in error

OkHttp in android for making network requests

Python Requests to Java OkHttp for Android

Error while sending HTTP GET requests using Volley in Android

Sending multiple duplicate PUT requests

Sending POST requests using Cookies

Picasso using OKHttp possible to cache all requests?

Swift sending multiple HTTP POST requests synchronously

Sending multiple requests simultaneously and waiting to collect results

Apache HttpAsynClient not sending multiple requests asynchronously

Wordpress sending multiple AJAX requests on one click

Sending multiple http post requests in loop

requestQueue volley doenst work (sending multiple requests)

Chat App - Sending multiple simultaneous requests to MongoDB

Sending message to Multiple Persons using send intent android

Sending multiple return values in python and get in android using chaquopy

sending push notifications to multiple android devices using GCM

sending push notification to multiple users using Parse in android

Requests are failing sending from installed APK, but working fine using the simulator and same phone connected to Android Studio, why?

Sending a Collection of requests for Distance matrix in android

Sending API requests from MusicBrowserServiceCompat in Android Auto

using threading for multiple requests

Sending get request using python-requests

Sending images by POST using python requests

Sending SOAP request using Python Requests

Sending Requests To Mobile Sites Using HttpClient

Having trouble sending requests using AFNetWorking

Sending cookie with attributes using python requests