Upload Image using okHttp

Many developer facing the problem with upload image using okHttp.So here is the clear solution which works with every OS.You just need to implement this "Multipart Request" class.

OPTION 1 : First of all Download the OkHttp dependency and paste it into your build.gradle file.


dependencies {
   compile 'com.squareup.okhttp3:okhttp:3.7.0'
}


OPTION 2 : Or If you have .jar file for OkHttp then put it into libs folder and then paste the below code in build.gradle file.

dependencies {
   compile files('libs/okhttp-3.7.0.jar')
}

 
You can choose any option from above either options 1 dependency or option 2 jar file choice is yours.
Now, add useLibrary Http legacy in build.gradle file inside android method.

android {
    useLibrary 'org.apache.http.legacy'
}

Now let us create a class with the name of "MultipartRequest" and paste the below code.
import android.content.Context;
import android.util.Log;

import org.apache.http.HttpStatus;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MultipartRequest
{
    public Context context;
    public MultipartBody.Builder multipartBody;
    public OkHttpClient okHttpClient;

    public MultipartRequest(Context context)

   {
        this.context = context;
        this.multipartBody = new MultipartBody.Builder();
        this.multipartBody.setType(MultipartBody.FORM);
        this.okHttpClient = new OkHttpClient();
    }

    // Add String
    public void addString(String name, String value)

    {
        this.multipartBody.addFormDataPart(name, value);
    }

    // Add Image File
    public void addFile(String name, String filePath, String fileName)

    {
        this.multipartBody.addFormDataPart(name, fileName, RequestBody.create(MediaType.parse("image/jpeg"), new File(filePath)));
    }

    // Add Zip File
    public void addZipFile(String name, String filePath, String fileName)

    {
        this.multipartBody.addFormDataPart(name, fileName, RequestBody.create(MediaType.parse("application/zip"), new File(filePath)));
    }

    // Execute Url
    public String execute(String url)
    {
        RequestBody requestBody = null;
        Request request = null;
        Response response = null;
        int code = 200;
        String strResponse = null;

        try
        {
            requestBody = this.multipartBody.build();
            // Set Your Authentication key here.
            request = new Request.Builder().header("Key", "Value").url(url).post(requestBody).build();

            Log.v("====== REQUEST ======",""+request);
            response = okHttpClient.newCall(request).execute();
            Log.v("====== RESPONSE ======",""+response);

            if (!response.isSuccessful())
                throw new IOException();

            code = response.networkResponse().code();

            /*
             * "Successful response from server"
             */
            if (response.isSuccessful())
            {
                strResponse =response.body().string();
            }
            /*
             * "Invalid URL or Server not available, please try again."
             */
            else if (code == HttpStatus.SC_NOT_FOUND)
            {
                strResponse = "Invalid URL or Server not available, please try again";
            }
            /*
             * "Connection timeout, please try again."
             */
            else if (code == HttpStatus.SC_REQUEST_TIMEOUT)
            {
                strResponse = "Connection timeout, please try again";
            }
            /*
             * "Invalid URL or Server is not responding, please try again."
             */
            else if (code == HttpStatus.SC_SERVICE_UNAVAILABLE)
            {
                strResponse = "Invalid URL or Server is not responding, please try again";
            }
        }
        catch (Exception e)
        {
            Log.e("Exception", e.getMessage());
        }
        finally
        {
            requestBody = null;
            request = null;
            response = null;
            multipartBody = null;
            if (okHttpClient != null)
                okHttpClient = null;

            System.gc();
        }
        return strResponse;
    }
}
 
 


And you are ready to use MultipartRequest for uploading files, Images, zip etc.
See the below code how you use it this class.You can use this with Volley, Asynctask etc.I show here the simple method and everything is up to you whether you use it using Asynctask or some other way.

MultipartRequest multipartRequest;

multipartRequest = new MultipartRequest(context);
multipartRequest.addFile("Your key name","Your image Path","Your file name");
multipartRequest.execute("Your Url");



Note : If you are using old OkHttp which is below version 3 then MultipartBody is not supported.In that case you have to use MultipartBuilder instead of MultipartBody.If you wish to code with MultipartBuilder here is my stackoverflow answer.


Comments

Post a Comment

Popular posts from this blog

How to blur background images?

How to remove a particular activity from android stack?