Fuel
The easiest HTTP networking library for Kotlin/Android.
Features
- Support basic HTTP GET/POST/PUT/DELETE/HEAD/PATCH in a fluent style interface
- Support both asynchronous and blocking requests
- Download file
- Upload file (multipart/form-data)
- Cancel in-flight request
- Request timeout
- Configuration manager by using FuelManager
- Debug log / cUrl log
- Support response deserialization into plain old object (both Kotlin & Java)
- Automatically invoke handler on Android Main Thread when using Android Module
- Special test mode for easier testing
- RxJava 2.x support out of the box
- Google Components LiveData support
- Built-in object serialization module (Gson, Jackson, Moshi, Forge) sparkles
- Support Kotlin's Coroutines module
- API Routing
Installation
Dependency - fuel
- Result - The modelling for success/failure of operations in Kotlin
Dependency - fuel-android
- Android SDK - Android SDK
Dependency - fuel-livedata
- Live Data - Android Architecture Components - LiveData
Dependency - fuel-rxjava
- RxJava - RxJava – Reactive Extensions for the JVM
Dependency - fuel-coroutines
- Coroutines - Kotlin Coroutines - Library support for Kotlin coroutines
Dependency - fuel-gson
- Gson - Gson - A Java serialization/deserialization library to convert Java Objects into JSON and back
Dependency - fuel-jackson
- Jackson - Jackson - The JSON library for Java
Dependency - fuel-moshi
- Moshi - Moshi - A modern JSON library for Android and Java
Dependency - fuel-forge
- Forge - Forge - Functional style JSON parsing written in Kotlin
Gradle
Sample
- There are two samples, one is in Kotlin and another one in Java.
Quick Glance Usage
Async mode
- Kotlin
- Java
Blocking mode
You can also wait for the response. It returns the same parameters as the async version, but it blocks the thread. It supports all the features of the async version.
- Kotlin
- Java
Detail Usage
GET
Response Handling
Result
-
Result is a functional style data structure that represents data that contains result of Success or Failure but not both. It represents the result of an action that can be success (with result) or error.
-
Working with result is easy. You could fold, destructure as because it is just a data class or do a simple
when
checking whether it is Success or Failure.
Response
Response in String
Response in Json
requires the android extension
Response in T (object)
POST
PUT
DELETE
HEAD
PATCH
- The default
client
isHttpClient
which is a thin wrapper overjava.net.HttpUrlConnnection
.java.net.HttpUrlConnnection
does not support aPATCH
method.HttpClient
convertsPATCH
requests to aPOST
request and adds aX-HTTP-Method-Override: PATCH
header. While this is a semi-standard industry practice not all APIs are configured to accept this header by default.
Debug Logging
- Use
toString()
method to Log (request|response)
//print and header detail
//request
--> GET (http://httpbin.org/get?key=value)
Body : (empty)
Headers : (2)
Accept-Encoding : compress;q=0.5, gzip;q=1.0
Device : Android
//response
<-- 200 (http://httpbin.org/get?key=value)
- Also support cUrl string to Log request, make it very easy to cUrl on command line
Parameter Support
- URL encoded style for GET & DELETE request
- Array support for GET requests
- Support x-www-form-urlencoded for PUT & POST
Set request's timeout and read timeout
Default timeout for a request is 15000 milliseconds.
Default read timeout for a request is 15000 milliseconds.
- Kotlin
- Java
Download with or without progress handler
Upload with or without progress handler
Specify custom field names for files
Upload a multipart form without a file
Upload from an InputStream
Authentication
- Support Basic Authentication right off the box
Validation
- By default, the valid range for HTTP status code will be (200..299).
Cancel
- If one wants to cancel on-going request, one could call
cancel
on the request object
- Also, interrupt request can be further processed with interrupt callback
Advanced Configuration
Response Deserialization
- Fuel provides built-in support for response deserialization. Here is how one might want to use Fuel together with Gson
Gson Deserialization
- Fuel also provides a built in support for Gson Deserialization. This is possible by including the Gson module in your dependency block.
- There are 4 methods to support response deserialization depending on your needs (also depending on JSON parsing library of your choice), and you are required to implement only one of them.
- Another example may be parsing a website that is not UTF-8. By default, Fuel serializes text as UTF-8, we need to define our deserializer as such
Configuration
-
Use singleton
FuelManager.instance
to manage global configurations. -
basePath
is used to manage common root path. Great usage is for your static API endpoint.
baseHeaders
is to manage common HTTP header pairs in format ofMap<String, String>>
.
-
Headers
can be add to a request via the methodsfun header(pairs: Map<String, Any>?): Request
orfun header(vararg pairs: Pair<String, Any>?)
. -
The latter method does support multiple values for the same key however as
fun header(pairs: Map<String, Any>?): Request
takes a map this method can not support multiple
values for the same key as per the definition of the map.
baseParams
is used to manage commonkey=value
query param, which will be automatically included in all of your subsequent requests in format ofList<Pair<String, Any?>>
(Any
is converted toString
bytoString()
method)
-
client
is a raw HTTP client driver. Generally, it is responsible to makeRequest
intoResponse
. Default isHttpClient
which is a thin wrapper overjava.net.HttpUrlConnnection
. You could use any httpClient of your choice by conforming toclient
protocol, and set back toFuelManager.instance
to kick off the effect. -
keyStore
is configurable by user. By default it isnull
. -
socketFactory
can be supplied by user. IfkeyStore
is not null,socketFactory
will be derived from it. -
hostnameVerifier
is configurable by user. By default, it usesHttpsURLConnection.getDefaultHostnameVerifier()
. -
requestInterceptors
responseInterceptors
is a side-effect to add toRequest
and/orResponse
objects. For example, one might wanna print cUrlString style for every request that hits server in DEBUG mode.
- Another example is that you might wanna add data into your Database, you can achieve that with providing
responseInterceptors
such as
Test mode
Testing asynchronized calls can be somehow hard without special care. That's why Fuel has a special test mode with make all the requests blocking, for tests.
In order to disable test mode, just call Fuel.regularMode()
RxJava Support
- Fuel supports RxJava right off the box.
- There are 6 extensions over
Request
that provide RxJava 2.xSingle<Result<T, FuelError>>
as return type.
LiveData Support
- Fuel supports LiveData
Routing Support
In order to organize better your network stack FuelRouting interface allows you to easily setup a Router design pattern.
Coroutines Support
Coroutines module provides extension functions to wrap a response inside a coroutine and handle its result. The coroutines-based API provides equivalent methods to the standard API (e.g: responseString()
in coroutines is awaitStringResponse()
).
There are functions to handle Result
object directly too.
It also provides useful methods to retrieve the ByteArray
,String
or Object
directly. The difference with these implementations is that they throw exception instead of returning it wrapped a FuelError
instance.
Handling objects other than String
(awaitStringResponse()
) or ByteArray
(awaitByteArrayResponse()
) can be done using awaitObject
, awaitObjectResult
or awaitObjectResponse
.