Wednesday, December 28, 2016

File upload using OkHttp and Cookie Manager in Android

OkHttp is a modern application network,  OkHttp will help making network calls efficiently, makes our stuffs load faster and saves the BandWidth.

Some of the advantages listed by OkHttp are :


  • Connection pooling reduces the request latency.
  • Transparent GZIP shrinks download sizes.
  • Response cashing avoids the network completely for repeat requests.
  • It supports both synchronous blocking calls & asych calls with callbacks .
  • OkHttp supports Android 2.3 and Above. For JAVA the minimum requirements is 1.7


    Here are the steps to Introduce the OkHttp an Http Client to your Android applications.

    Here are the steps to integrate the OkHttp library
    Step 1: Add the dependencies
       `compile 'com.squareup.okhttp3:okhttp:3.4.1`
    
        compile 'com.squareup.okhttp3:okhttp-urlconnection:3.0.0-RC1'`
    Step 2 : Import the following java classes one of your package

                 If your trying to upload the files/images using the cookie manager
    (Copy the code from following links and use it)

    File1 : Serializablehttpcookie
    File2 : Persistentcookiestore
    File3 : Htplogginginterceptor


    Step 3 : Make API requests

    using the following methods
    public static String sendRequest(Context context, String OPERATION, RequestBody requestBody) {
    
            String resp_str = null;
    
            Request request = new Request.Builder()
                    .url(context.getString(R.string.api_url) + OPERATION)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .method("POST", RequestBody.create(null, new byte[0]))
                    .post(requestBody)
                    .build();
    
            try {
                CookieHandler cookieHandler = new CookieManager(new PersistentCookieStore(context), CookiePolicy.ACCEPT_ALL);
                HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    
                OkHttpClient okHttpClient = new OkHttpClient()
                        .newBuilder()
                        .cookieJar(new JavaNetCookieJar(cookieHandler))
                        .addInterceptor(logging)
                        .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                        .build();
    
    
    
                Response response = okHttpClient.newCall(request).execute();
    
                resp_str = response.body().string();
    
               response.body().close();
    
                LogDumper.e(TAG+"="+OPERATION, resp_str);
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
    
            return resp_str;
        }
    
    //Method to upload file with request body
        public static String upload(RequestBody requestBody, String OPERATION )
        {
            String response=null;
            try {
    
                CookieHandler cookieHandler = new CookieManager(new PersistentCookieStore(context), CookiePolicy.ACCEPT_ALL);
                HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    
                OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                        .cookieJar(new JavaNetCookieJar(cookieHandler))
                        .addInterceptor(logging)
                        .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                        .build();
    
    
                Request request = new Request.Builder()
                        .url(context.getString(R.string.api_url) + OPERATION)
                        .addHeader("Content-Type", "multipart/form-data")
                        .post(requestBody)
                        .build();
    
    
                Response response1 = okHttpClient.newCall(request).execute();
    
                response =  response1.body().string();
                LogDumper.e(TAG+"="+OPERATION, response);
    
                response1.body().close();
    
    
            } catch (IOException e) {
                e.printStackTrace();
                return null ;
            }
    
            return response;
        }
    
    

0 comments:

Post a Comment