Convert Figma logo to code with AI

amitshekhariitbhu logoFast-Android-Networking

🚀 A Complete Fast Android Networking Library that also supports HTTP/2 🚀

5,674
956
5,674
228

Top Related Projects

45,699

Square’s meticulous HTTP client for the JVM, Android, and GraalVM.

43,026

A type-safe HTTP client for Android and the JVM

3,378

An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries.

Asynchronous Http and WebSocket Client library for Java

6,294

Android Asynchronous Networking and Image Loading

Quick Overview

Fast Android Networking is a powerful Android networking library built on top of OkHttp. It offers a simple and fast way to make HTTP requests, handle responses, and manage caching in Android applications. The library provides both synchronous and asynchronous request options, along with support for various data types and file uploads/downloads.

Pros

  • Easy to use API with a fluent interface for building requests
  • Built-in support for caching, including customizable cache control
  • Efficient handling of image loading and caching
  • Supports both RxJava and Kotlin Coroutines for asynchronous programming

Cons

  • Limited documentation compared to some other networking libraries
  • May have a steeper learning curve for developers new to networking concepts
  • Fewer community contributions and updates compared to more popular libraries
  • Some advanced features might require additional setup or configuration

Code Examples

  1. Making a simple GET request:
AndroidNetworking.get("https://api.example.com/data")
    .build()
    .getAsJSONObject(object : JSONObjectRequestListener {
        override fun onResponse(response: JSONObject) {
            // Handle successful response
        }
        override fun onError(error: ANError) {
            // Handle error
        }
    })
  1. Uploading a file:
AndroidNetworking.upload("https://api.example.com/upload")
    .addMultipartFile("file", File("/path/to/file"))
    .build()
    .setUploadProgressListener { bytesUploaded, totalBytes ->
        // Update upload progress
    }
    .getAsJSONObject(object : JSONObjectRequestListener {
        override fun onResponse(response: JSONObject) {
            // Handle successful upload
        }
        override fun onError(error: ANError) {
            // Handle error
        }
    })
  1. Using RxJava for asynchronous requests:
AndroidNetworking.get("https://api.example.com/data")
    .build()
    .getAsJSONObjectObservable()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(
        { response -> /* Handle successful response */ },
        { error -> /* Handle error */ }
    )

Getting Started

  1. Add the dependency to your app's build.gradle file:
dependencies {
    implementation 'com.amitshekhar.android:android-networking:1.0.2'
}
  1. Initialize the library in your Application class:
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        AndroidNetworking.initialize(applicationContext)
    }
}
  1. Make sure to add internet permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />

Now you can start using Fast Android Networking in your Android project!

Competitor Comparisons

45,699

Square’s meticulous HTTP client for the JVM, Android, and GraalVM.

Pros of OkHttp

  • More mature and widely adopted in the Android ecosystem
  • Extensive documentation and community support
  • Highly customizable with interceptors and connection pools

Cons of OkHttp

  • Requires more boilerplate code for basic operations
  • Steeper learning curve for beginners
  • Less built-in support for image loading and caching

Code Comparison

Fast-Android-Networking:

AndroidNetworking.get("https://api.example.com/data")
    .addQueryParameter("param", "value")
    .build()
    .getAsJSONObject(new JSONObjectRequestListener() {
        @Override
        public void onResponse(JSONObject response) {
            // Handle response
        }
    });

OkHttp:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url("https://api.example.com/data?param=value")
    .build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // Handle response
    }
});

Fast-Android-Networking provides a more concise API for common networking tasks, while OkHttp offers greater flexibility and control over the networking process. Fast-Android-Networking is built on top of OkHttp, adding convenience methods and features specifically tailored for Android development. OkHttp, being a lower-level library, is more suitable for complex networking scenarios and can be used in both Android and Java projects.

43,026

A type-safe HTTP client for Android and the JVM

Pros of Retrofit

  • More mature and widely adopted in the Android community
  • Extensive documentation and community support
  • Highly customizable with various converters and adapters

Cons of Retrofit

  • Steeper learning curve for beginners
  • Requires more boilerplate code for simple requests
  • Less built-in features compared to Fast-Android-Networking

Code Comparison

Fast-Android-Networking:

AndroidNetworking.get("https://api.example.com/users")
    .addQueryParameter("limit", "3")
    .build()
    .getAsJSONArray(new JSONArrayRequestListener() {
        @Override
        public void onResponse(JSONArray response) {
            // Handle response
        }
    });

Retrofit:

@GET("users")
Call<List<User>> getUsers(@Query("limit") int limit);

// Usage
Call<List<User>> call = apiService.getUsers(3);
call.enqueue(new Callback<List<User>>() {
    @Override
    public void onResponse(Call<List<User>> call, Response<List<User>> response) {
        // Handle response
    }
});

Both libraries offer efficient networking solutions for Android, but Retrofit provides more flexibility and customization options at the cost of a steeper learning curve. Fast-Android-Networking offers a simpler API with built-in features, making it easier for beginners to get started with network requests in Android applications.

3,378

Pros of Volley

  • Developed and maintained by Google, ensuring long-term support and updates
  • Seamless integration with other Google libraries and Android ecosystem
  • Built-in request prioritization and cancellation

Cons of Volley

  • Limited support for large data transfers and file downloads
  • Lacks advanced features like request chaining and easy customization
  • Slower performance compared to Fast Android Networking in some scenarios

Code Comparison

Fast Android Networking:

AndroidNetworking.get("https://api.example.com/data")
    .addQueryParameter("key", "value")
    .setPriority(Priority.MEDIUM)
    .build()
    .getAsJSONObject(new JSONObjectRequestListener() {
        @Override
        public void onResponse(JSONObject response) {
            // Handle response
        }
    });

Volley:

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
    (Request.Method.GET, "https://api.example.com/data", null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            // Handle response
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // Handle error
        }
    });
requestQueue.add(jsonObjectRequest);

Fast Android Networking offers a more concise and readable syntax, with built-in support for query parameters and priority setting. Volley requires more boilerplate code and separate error handling, but provides direct access to the underlying request object for advanced customization.

An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries.

Pros of android-async-http

  • More mature and established library with a longer history
  • Extensive documentation and community support
  • Lightweight and easy to integrate into existing projects

Cons of android-async-http

  • Less active development and fewer recent updates
  • Limited support for modern Android features and best practices
  • Lacks some advanced features like caching and request prioritization

Code Comparison

android-async-http:

AsyncHttpClient client = new AsyncHttpClient();
client.get("https://api.example.com/data", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        // Handle success
    }
    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        // Handle failure
    }
});

Fast-Android-Networking:

AndroidNetworking.get("https://api.example.com/data")
    .build()
    .getAsJSONObject(new JSONObjectRequestListener() {
        @Override
        public void onResponse(JSONObject response) {
            // Handle success
        }
        @Override
        public void onError(ANError error) {
            // Handle error
        }
    });

Fast-Android-Networking offers a more modern and concise syntax, with built-in support for JSON parsing. It also provides additional features like request cancellation, caching, and better error handling. However, android-async-http may be more suitable for developers who prefer a more traditional approach or need to maintain legacy projects.

Asynchronous Http and WebSocket Client library for Java

Pros of async-http-client

  • More mature and widely used in Java ecosystem
  • Supports multiple protocols (HTTP, WebSocket, Server-Sent Events)
  • Highly configurable with extensive documentation

Cons of async-http-client

  • Not specifically designed for Android, may require additional setup
  • Larger library size, potentially impacting app size
  • Steeper learning curve for Android developers

Code Comparison

async-http-client:

AsyncHttpClient client = new DefaultAsyncHttpClient();
client.prepareGet("http://example.com")
    .execute()
    .toCompletableFuture()
    .thenAccept(response -> System.out.println(response.getResponseBody()));

Fast-Android-Networking:

AndroidNetworking.get("http://example.com")
    .build()
    .getAsString(new StringRequestListener() {
        @Override
        public void onResponse(String response) {
            System.out.println(response);
        }
    });

Fast-Android-Networking offers a more Android-centric API with simpler syntax for common tasks. It includes features like easy image loading and caching out of the box. However, async-http-client provides more flexibility and is better suited for complex networking scenarios across different Java environments.

Fast-Android-Networking is optimized for Android, resulting in smaller app size and better performance on mobile devices. It also integrates well with other Android libraries and patterns.

Both libraries support asynchronous operations, but Fast-Android-Networking's API is generally more intuitive for Android developers, while async-http-client offers more advanced features for power users.

6,294

Android Asynchronous Networking and Image Loading

Pros of Ion

  • More mature and established library with a longer history
  • Supports a wider range of features, including file downloads and uploads
  • Offers more flexible caching options

Cons of Ion

  • Less actively maintained compared to Fast-Android-Networking
  • Larger library size, which may impact app size
  • Slightly more complex API for basic operations

Code Comparison

Fast-Android-Networking:

AndroidNetworking.get("https://api.example.com/data")
    .setPriority(Priority.HIGH)
    .build()
    .getAsJSONObject(new JSONObjectRequestListener() {
        @Override
        public void onResponse(JSONObject response) {
            // Handle response
        }
    });

Ion:

Ion.with(context)
    .load("https://api.example.com/data")
    .asJsonObject()
    .setCallback(new FutureCallback<JsonObject>() {
        @Override
        public void onCompleted(Exception e, JsonObject result) {
            // Handle response
        }
    });

Both libraries offer similar functionality for basic network operations, but Ion provides a more fluent API style. Fast-Android-Networking focuses on simplicity and ease of use, while Ion offers more advanced features and customization options. The choice between the two depends on the specific requirements of your project and personal preference for API design.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

<img src=https://raw.githubusercontent.com/amitshekhariitbhu/Fast-Android-Networking/master/assets/androidnetworking.png >

Fast Android Networking Library

About Fast Android Networking Library

Fast Android Networking Library is a powerful library for doing any type of networking in Android applications which is made on top of OkHttp Networking Layer.

Fast Android Networking Library takes care of each and everything. So you don't have to do anything, just make request and listen for the response.

Why use Fast Android Networking ?

  • Recent removal of HttpClient in Android Marshmallow(Android M) made other networking libraries obsolete.
  • No other single library does each and everything like making request, downloading any type of file, uploading file, loading image from network in ImageView, etc. There are some libraries but they are outdated.
  • No other library provides simple interface for doing all types of things in networking like setting priority, cancelling, etc.
  • As it uses Okio , No more GC overhead in android applications. Okio is made to handle GC overhead while allocating memory. Okio does some clever things to save CPU and memory.
  • It uses OkHttp , more importantly it supports HTTP/2.

About me

Hi, I am Amit Shekhar, Co-Founder @ Outcome School • IIT 2010-14 • I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

You can connect with me on:

Outcome School Blog - High-quality content to learn Android concepts.

RxJava2 Support, check here.

Find this project useful ? :heart:

  • Support it by clicking the :star: button on the upper right of this page. :v:

For full details, visit the documentation on our web site :

Requirements

Fast Android Networking Library can be included in any Android application.

Fast Android Networking Library supports Android 2.3 (Gingerbread) and later.

Using Fast Android Networking Library in your application

Add this in your settings.gradle:

maven { url 'https://jitpack.io' }

If you are using settings.gradle.kts, add the following:

maven { setUrl("https://jitpack.io") }

Add this in your build.gradle

implementation 'com.github.amitshekhariitbhu.Fast-Android-Networking:android-networking:1.0.4'

If you are using build.gradle.kts, add the following:

implementation("com.github.amitshekhariitbhu.Fast-Android-Networking:android-networking:1.0.4")

Do not forget to add internet permission in manifest if already not present

<uses-permission android:name="android.permission.INTERNET" />

Then initialize it in onCreate() Method of application class :

AndroidNetworking.initialize(getApplicationContext());

Initializing it with some customization , as it uses OkHttp as networking layer, you can pass custom okHttpClient while initializing it.

// Adding an Network Interceptor for Debugging purpose :
OkHttpClient okHttpClient = new OkHttpClient() .newBuilder()
                        .addNetworkInterceptor(new StethoInterceptor())
                        .build();
AndroidNetworking.initialize(getApplicationContext(),okHttpClient);                        

Using the Fast Android Networking with Jackson Parser

Add this in your build.gradle

implementation 'com.github.amitshekhariitbhu.Fast-Android-Networking:jackson-android-networking:1.0.4'

If you are using build.gradle.kts, add the following:

implementation("com.github.amitshekhariitbhu.Fast-Android-Networking:jackson-android-networking:1.0.4")
// Then set the JacksonParserFactory like below
AndroidNetworking.setParserFactory(new JacksonParserFactory());

Using the Fast Android Networking with RxJava2

Add this in your build.gradle

implementation 'com.github.amitshekhariitbhu.Fast-Android-Networking:rx2-android-networking:1.0.4'

If you are using build.gradle.kts, add the following:

implementation("com.github.amitshekhariitbhu.Fast-Android-Networking:rx2-android-networking:1.0.4")

Using the Fast Android Networking with RxJava

Add this in your build.gradle

implementation 'com.github.amitshekhariitbhu.Fast-Android-Networking:rx-android-networking:1.0.4'

If you are using build.gradle.kts, add the following:

implementation("com.github.amitshekhariitbhu.Fast-Android-Networking:rx-android-networking:1.0.4")

Making a GET Request

AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                 .addPathParameter("pageNumber", "0")
                 .addQueryParameter("limit", "3")
                 .addHeaders("token", "1234")
                 .setTag("test")
                 .setPriority(Priority.LOW)
                 .build()
                 .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });                

Making a POST Request

AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createAnUser")
                 .addBodyParameter("firstname", "Amit")
                 .addBodyParameter("lastname", "Shekhar")
                 .setTag("test")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });

You can also post java object, json, file, etc in POST request like this.

User user = new User();
user.firstname = "Amit";
user.lastname = "Shekhar";

AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser")
                 .addBodyParameter(user) // posting java object
                 .setTag("test")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });


JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("firstname", "Amit");
    jsonObject.put("lastname", "Shekhar");
} catch (JSONException e) {
  e.printStackTrace();
}
       
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/createUser")
                 .addJSONObjectBody(jsonObject) // posting json
                 .setTag("test")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });
                
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/postFile")
                 .addFileBody(file) // posting any type of file
                 .setTag("test")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });               

Using it with your own JAVA Object - JSON Parser

/*--------------Example One -> Getting the userList----------------*/
AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                .addPathParameter("pageNumber", "0")
                .addQueryParameter("limit", "3")
                .setTag(this)
                .setPriority(Priority.LOW)
                .build()
                .getAsObjectList(User.class, new ParsedRequestListener<List<User>>() {
                    @Override
                    public void onResponse(List<User> users) {
                      // do anything with response
                      Log.d(TAG, "userList size : " + users.size());
                      for (User user : users) {
                        Log.d(TAG, "id : " + user.id);
                        Log.d(TAG, "firstname : " + user.firstname);
                        Log.d(TAG, "lastname : " + user.lastname);
                      }
                    }
                    @Override
                    public void onError(ANError anError) {
                     // handle error
                    }
                });
/*--------------Example Two -> Getting an user----------------*/
AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}")
                .addPathParameter("userId", "1")
                .setTag(this)
                .setPriority(Priority.LOW)
                .build()
                .getAsObject(User.class, new ParsedRequestListener<User>() {
                     @Override
                     public void onResponse(User user) {
                        // do anything with response
                        Log.d(TAG, "id : " + user.id);
                        Log.d(TAG, "firstname : " + user.firstname);
                        Log.d(TAG, "lastname : " + user.lastname);
                     }
                     @Override
                     public void onError(ANError anError) {
                        // handle error
                     }
                 }); 
/*-- Note : YourObject.class, getAsObject and getAsObjectList are important here --*/              

Downloading a file from server

AndroidNetworking.download(url,dirPath,fileName)
                 .setTag("downloadTest")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .setDownloadProgressListener(new DownloadProgressListener() {
                    @Override
                    public void onProgress(long bytesDownloaded, long totalBytes) {
                      // do anything with progress  
                    }
                 })
                 .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                      // do anything after completion
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error    
                    }
                });                 

Uploading a file to server

AndroidNetworking.upload(url)
                 .addMultipartFile("image",file)    
                 .addMultipartParameter("key","value")
                 .setTag("uploadTest")
                 .setPriority(Priority.HIGH)
                 .build()
                 .setUploadProgressListener(new UploadProgressListener() {
                    @Override
                    public void onProgress(long bytesUploaded, long totalBytes) {
                      // do anything with progress 
                    }
                 })
                 .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // do anything with response                
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error 
                    }
                 }); 

Getting Response and completion in an another thread executor

(Note : Error and Progress will always be returned in main thread of application)

AndroidNetworking.upload(url)
                 .addMultipartFile("image",file)  
                 .addMultipartParameter("key","value")  
                 .setTag("uploadTest")
                 .setPriority(Priority.HIGH)
                 .build()
                 .setExecutor(Executors.newSingleThreadExecutor()) // setting an executor to get response or completion on that executor thread
                 .setUploadProgressListener(new UploadProgressListener() {
                    @Override
                    public void onProgress(long bytesUploaded, long totalBytes) {
                      // do anything with progress 
                    }
                 })
                 .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                      // below code will be executed in the executor provided
                      // do anything with response                
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error 
                    }
                 }); 

Setting a Percentage Threshold For Not Cancelling the request if it has completed the given threshold

AndroidNetworking.download(url,dirPath,fileName)
                 .setTag("downloadTest")
                 .setPriority(Priority.MEDIUM)
                 .setPercentageThresholdForCancelling(50) // even if at the time of cancelling it will not cancel if 50% 
                 .build()                                 // downloading is done.But can be cancalled with forceCancel.
                 .setDownloadProgressListener(new DownloadProgressListener() {
                    @Override
                    public void onProgress(long bytesDownloaded, long totalBytes) {
                      // do anything with progress  
                    }
                 })
                 .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                      // do anything after completion
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error    
                    }
                });   

Cancelling a request.

Any request with a given tag can be cancelled. Just do like this.

AndroidNetworking.cancel("tag"); // All the requests with the given tag will be cancelled.
AndroidNetworking.forceCancel("tag");  // All the requests with the given tag will be cancelled , even if any percent threshold is
                                       // set , it will be cancelled forcefully. 
AndroidNetworking.cancelAll(); // All the requests will be cancelled.  
AndroidNetworking.forceCancelAll(); // All the requests will be cancelled , even if any percent threshold is
                               // set , it will be cancelled forcefully.                           

Loading image from network into ImageView

      <com.androidnetworking.widget.ANImageView
          android:id="@+id/imageView"
          android:layout_width="100dp"
          android:layout_height="100dp"
          android:layout_gravity="center" />
          
      imageView.setDefaultImageResId(R.drawable.default);
      imageView.setErrorImageResId(R.drawable.error);
      imageView.setImageUrl(imageUrl);          

Getting Bitmap from url with some specified parameters

AndroidNetworking.get(imageUrl)
                 .setTag("imageRequestTag")
                 .setPriority(Priority.MEDIUM)
                 .setBitmapMaxHeight(100)
                 .setBitmapMaxWidth(100)
                 .setBitmapConfig(Bitmap.Config.ARGB_8888)
                 .build()
                 .getAsBitmap(new BitmapRequestListener() {
                    @Override
                    public void onResponse(Bitmap bitmap) {
                    // do anything with bitmap
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error
                    }
                });

Error Code Handling

public void onError(ANError error) {
   if (error.getErrorCode() != 0) {
        // received error from server
        // error.getErrorCode() - the error code from server
        // error.getErrorBody() - the error body from server
        // error.getErrorDetail() - just an error detail
        Log.d(TAG, "onError errorCode : " + error.getErrorCode());
        Log.d(TAG, "onError errorBody : " + error.getErrorBody());
        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
        // get parsed error object (If ApiError is your class)
        ApiError apiError = error.getErrorAsObject(ApiError.class);
   } else {
        // error.getErrorDetail() : connectionError, parseError, requestCancelledError
        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
   }
}

Remove Bitmap from cache or clear cache

AndroidNetworking.evictBitmap(key); // remove a bitmap with key from LruCache
AndroidNetworking.evictAllBitmap(); // clear LruCache

Prefetch a request (so that it can return from cache when required at instant)

AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                .addPathParameter("pageNumber", "0")
                .addQueryParameter("limit", "30")
                .setTag(this)
                .setPriority(Priority.LOW)
                .build()
                .prefetch();

Customizing OkHttpClient for a particular request

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .addInterceptor(new GzipRequestInterceptor())
                .build();
                
AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                 .addPathParameter("pageNumber", "0")
                 .addQueryParameter("limit", "3")
                 .addHeaders("token", "1234")
                 .setTag("test")
                 .setPriority(Priority.LOW)
                 .setOkHttpClient(okHttpClient) // passing a custom okHttpClient 
                 .build()
                 .getAsJSONArray(new JSONArrayRequestListener() {
                    @Override
                    public void onResponse(JSONArray response) {
                      // do anything with response
                    }
                    @Override
                    public void onError(ANError error) {
                    // handle error
                    }
                });

Making a conditional request (Building a request)

ANRequest.GetRequestBuilder getRequestBuilder = new ANRequest.GetRequestBuilder(ApiEndPoint.BASE_URL + ApiEndPoint.CHECK_FOR_HEADER);
               
if(isHeaderRequired){
 getRequestBuilder.addHeaders("token", "1234");
}

if(executorRequired){
 getRequestBuilder.setExecutor(Executors.newSingleThreadExecutor());
}
               
ANRequest anRequest = getRequestBuilder.build();       
                 
anRequest.getAsJSONObject(new JSONObjectRequestListener() {
    @Override
    public void onResponse(JSONObject response) {
      // do anything with response
    }
    @Override
    public void onError(ANError error) {
      // handle error
    }
});

ConnectionClass Listener to get current network quality and bandwidth

// Adding Listener
AndroidNetworking.setConnectionQualityChangeListener(new ConnectionQualityChangeListener() {
            @Override
            public void onChange(ConnectionQuality currentConnectionQuality, int currentBandwidth) {
              // do something on change in connectionQuality
            }
        });
        
// Removing Listener   
AndroidNetworking.removeConnectionQualityChangeListener();

// Getting current ConnectionQuality
ConnectionQuality connectionQuality = AndroidNetworking.getCurrentConnectionQuality();
if(connectionQuality == ConnectionQuality.EXCELLENT) {
  // do something
} else if (connectionQuality == ConnectionQuality.POOR) {
  // do something
} else if (connectionQuality == ConnectionQuality.UNKNOWN) {
  // do something
}
// Getting current bandwidth
int currentBandwidth = AndroidNetworking.getCurrentBandwidth(); // Note : if (currentBandwidth == 0) : means UNKNOWN

Getting Analytics of a request by setting AnalyticsListener on that

AndroidNetworking.download(url,dirPath,fileName)
                 .setTag("downloadTest")
                 .setPriority(Priority.MEDIUM)
                 .build()
                 .setAnalyticsListener(new AnalyticsListener() {
                      @Override
                      public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) {
                          Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
                          Log.d(TAG, " bytesSent : " + bytesSent);
                          Log.d(TAG, " bytesReceived : " + bytesReceived);
                          Log.d(TAG, " isFromCache : " + isFromCache);
                      }
                  })
                 .setDownloadProgressListener(new DownloadProgressListener() {
                    @Override
                    public void onProgress(long bytesDownloaded, long totalBytes) {
                      // do anything with progress  
                    }
                 })
                 .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                      // do anything after completion
                    }
                    @Override
                    public void onError(ANError error) {
                      // handle error    
                    }
                });  
Note : If bytesSent or bytesReceived is -1 , it means it is unknown                

Getting OkHttpResponse in Response

AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUserDetail/{userId}")
                .addPathParameter("userId", "1")
                .setTag(this)
                .setPriority(Priority.LOW)
                .setUserAgent("getAnUser")
                .build()
                .getAsOkHttpResponseAndParsed(new TypeToken<User>() {
                }, new OkHttpResponseAndParsedRequestListener<User>() {
                    @Override
                    public void onResponse(Response okHttpResponse, User user) {
                      // do anything with okHttpResponse and user
                    }
                    @Override
                    public void onError(ANError anError) {
                      // handle error
                    }
                });

Making Synchronous Request

ANRequest request = AndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}")
                        .addPathParameter("pageNumber", "0")
                        .addQueryParameter("limit", "3")
                        .build();
ANResponse<List<User>> response = request.executeForObjectList(User.class);
if (response.isSuccess()) {
   List<User> users = responseTwo.getResult();
} else {
   //handle error
}                                        

How caching works ?

  • First of all the server must send cache-control in header so that is starts working.
  • Response will be cached on the basis of cache-control max-age,max-stale.
  • If internet is connected and the age is NOT expired it will return from cache.
  • If internet is connected and the age is expired and if server returns 304(NOT MODIFIED) it will return from cache.
  • If internet is NOT connected if you are using getResponseOnlyIfCached() - it will return from cache even it date is expired.
  • If internet is NOT connected , if you are NOT using getResponseOnlyIfCached() - it will NOT return anything.
  • If you are using getResponseOnlyFromNetwork() , it will only return response after validation from server.
  • If cache-control is set, it will work according to the max-age,max-stale returned from server.
  • If internet is NOT connected only way to get cache Response is by using getResponseOnlyIfCached().

Enabling Logging

AndroidNetworking.enableLogging(); // simply enable logging
AndroidNetworking.enableLogging(LEVEL.HEADERS); // enabling logging with level

Enabling GZIP From Client to Server

// Enabling GZIP for Request (Not needed if your server doesn't support GZIP Compression), anyway responses 
// from server are automatically unGzipped if required. So enable it only if you need your request to be 
// Gzipped before sending to server(Make sure your server support GZIP Compression).
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .addInterceptor(new GzipRequestInterceptor())
                .build();
AndroidNetworking.initialize(getApplicationContext(),okHttpClient);                

IMPORTANT NOTE

  • Use IMMEDIATE Priority with caution - use is at appropriate place only when 1 or 2 (at max 2)IMMEDIATE request is required at instant.Otherwise use HIGH Priority.

  • Known Bug : As present if you are using GZIP Interceptor from client to server, Upload progress is not working perfectly in Multipart.

    If you are using Proguard with Gradle build system (which is usually the case), you don't have to do anything. The appropriate Proguard rules will be automatically applied. If you still need the rules applied in proguard-rules.pro, it is as follows:

    -dontwarn okio.**
    

Fast Android Networking Library supports

  • Fast Android Networking Library supports all types of HTTP/HTTPS request like GET, POST, DELETE, HEAD, PUT, PATCH
  • Fast Android Networking Library supports downloading any type of file
  • Fast Android Networking Library supports uploading any type of file (supports multipart upload)
  • Fast Android Networking Library supports cancelling a request
  • Fast Android Networking Library supports setting priority to any request (LOW, MEDIUM, HIGH, IMMEDIATE)
  • Fast Android Networking Library supports RxJava

As it uses OkHttp as a networking layer, it supports:

  • Fast Android Networking Library supports HTTP/2 support allows all requests to the same host to share a socket
  • Fast Android Networking Library uses connection pooling which reduces request latency (if HTTP/2 isn’t available)
  • Transparent GZIP shrinks download sizes
  • Fast Android Networking Library supports response caching which avoids the network completely for repeat requests

Difference over other Networking Library

  • In Fast Android Networking Library, OkHttpClient can be customized for every request easily — like timeout customization, etc. for each request.
  • As Fast Android Networking Library uses OkHttp and Okio, it is faster.
  • Single library for all type of networking.
  • Supports RxJava, RxJava2 -> Check here
  • Current bandwidth and connection quality can be obtained to decide logic of code.
  • Executor can be passed to any request to get the response in another thread.
  • Complete analytics of any request can be obtained.
  • All types of customization are possible.
  • Immediate Request really is immediate now.
  • Prefetching of any request can be done so that it gives instant data when required from the cache.
  • Proper request canceling.
  • Prevents cancellation of a request if it’s completed more than a specific threshold percentage.
  • A simple interface to make any type of request.
  • Proper Response Caching — which leads to reduced bandwidth usage.

TODO

  • Integration with other library
  • And of course many many features and bug fixes

CREDITS

Contact - Let's become friend

License

   Copyright (C) 2024 Amit Shekhar

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Contributing to Fast Android Networking

All pull requests are welcome, make sure to follow the contribution guidelines when you submit pull request.