v1.x.y
The easiest HTTP networking library for Kotlin/Android.
Features
Installation
There are 2 versions of Fuel build against different Kotlin Versions
Kotlin - 1.2.71
Coroutine - 0.23.3
Kotlin - 1.3.0-rc-146
Coroutine - 0.30.1-eap13
Dependency - fuel
Result - The modelling for success/failure of operations in Kotlin
Dependency - fuel-android
Android SDK - Android SDK
Min SDK: 19
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-kotlinx-serialization
Kotlinx Serialization - Kotlinx Serialization - Kotlin cross-platform / multi-format serialization
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
Dependency - fuel-reactor
Project Reactor - Project Reactor - Implementation of Reactive Streams standard
Gradle
Sample
There are two samples, one is in Kotlin and another one in Java.
Quick Glance Usage
Async mode
Kotlin
```kotlin
//an extension over string (support GET, PUT, POST, DELETE with httpGet(), httpPut(), httpPost(), httpDelete())
"https://httpbin.org/get".httpGet().responseString { request, response, result ->
//do something with response
when (result) {
is Result.Failure -> {
}
is Result.Success -> {
}
}
}
//if we set baseURL beforehand, simply use relativePath FuelManager.instance.basePath = "https://httpbin.org" "/get".httpGet().responseString { request, response, result -> //make a GET to https://httpbin.org/get and do something with response val (data, error) = result if (error == null) { //do something when success } else { //error handling } }
//if you prefer this a little longer way, you can always do //get Fuel.get("https://httpbin.org/get").responseString { request, response, result -> //do something with response result.fold({ d -> //do something with data }, { err -> //do something with error }) }
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
```java try { Triple data = Fuel.get("https://www.google.com").responseString(); Request request = data.getFirst(); Response response = data.getSecond(); Result text = data.getThird(); } catch (Exception networkError) {
}
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
whenchecking 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
clientisHttpClientwhich is a thin wrapper overjava.net.HttpUrlConnection.java.net.HttpUrlConnectiondoes not support a [PATCH](https://download.java.net/jdk7/archive/b123/docs/api/java/net/HttpURLConnection.html#setRequestMethod(java.lang.String)) method.HttpClientconvertsPATCHrequests to aPOSTrequest and adds aX-HTTP-Method-Override: PATCHheader. While this is a semi-standard industry practice not all APIs are configured to accept this header by default.
CONNECT
Connect is not supported by the Java JVM via the regular HTTP clients, and is therefore not supported.
OPTIONS
There are no convenience methods for making an OPTIONS request, but you can still make one directly:
TRACE
There are no convenience methods for making an TRACE request, but you can still make one directly:
Debug Logging
Use
toString()method to inspect requests
Use
toString()method to inspect responses
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
```kotlin
val timeout = 5000 // 5000 milliseconds = 5 seconds.
val timeoutRead = 60000 // 60000 milliseconds = 1 minute.
Fuel.get("https://httpbin.org/get") .timeout(timeout) .timeoutRead(timeoutRead) .responseString { request, response, result -> }
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
InputStreamAuthentication
Support Basic Authentication right off the box
Support Bearer Authentication
Support Any authentication by header
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
cancelon the request objectAlso, 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
```kotlin //User Model data class User(val firstName: String = "", val lastName: String = "") {
//User Deserializer class Deserializer : ResponseDeserializable { override fun deserialize(content: String) = Gson().fromJson(content, User::class.java) }
}
//Use httpGet extension "https://www.example.com/user/1".httpGet().responseObject(User.Deserializer()) { req, res, result -> //result is of type Result val (user, err) = result
}
Deserialization using kotlinx.serialzationn
requires the kotlinx-serialization extension requires kotlinx.serialization
This is by default strict and will reject unknown keys, for that you can pass a custom JSOn instance
JSON(nonstrict = true)
kotlinx.serialization can not always guess the correct serialzer to use, when generics are involved for example
It can be used with coroutines by using kotlinxDeserilaizerOf() it takes the same json and loader as parameters
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.instanceto manage global configurations.basePathis used to manage common root path. Great usage is for your static API endpoint.baseHeadersis to manage common HTTP header pairs in format ofMap<String, String>.The base headers are only applied if the request does not have those headers set.
Headerscan be added to a request via various methods includingfun header(name: String, value: Any): Request:request.header("foo", "a")fun header(pairs: Map<String, Any>): Request:request.header(mapOf("foo" to "a"))fun header(vararg pairs: Pair<String, Any>): Request:request.header("foo" to "a")operator fun set(header: String, value: Collection<Any>): Request:request["foo"] = listOf("a", "b")operator fun set(header: String, value: Any): Request:request["foo"] = "a"
By default, all subsequent calls overwrite earlier calls, but you may use the
appendHeadervariant to append values to existing values.In earlier versions a
mapOfoverwrote, andvarargs pairdid not, but this was confusing.
Some of the HTTP headers are defined under
Headers.Companionand can be used instead of literal strings.baseParamsis used to manage commonkey=valuequery param, which will be automatically included in all of your subsequent requests in format ofParameters(Anyis converted toStringbytoString()method)clientis a raw HTTP client driver. Generally, it is responsible to makeRequestintoResponse. Default isHttpClientwhich is a thin wrapper overjava.net.HttpUrlConnection. You could use any httpClient of your choice by conforming toclientprotocol, and set back toFuelManager.instanceto kick off the effect.keyStoreis configurable by user. By default it isnull.socketFactorycan be supplied by user. IfkeyStoreis not null,socketFactorywill be derived from it.hostnameVerifieris configurable by user. By default, it usesHttpsURLConnection.getDefaultHostnameVerifier().requestInterceptorsresponseInterceptorsis a side-effect to add toRequestand/orResponseobjects.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
responseInterceptorssuch 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
Requestthat 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.
Project Reactor
The Reactor module API provides functions starting with the prefix mono to handle instances of Response, Result<T, FuelError> and values directly (String, ByteArray, Any). All functions expose exceptions as FuelError instance.
Data handling example
Error handling example
Response handling example
Other libraries
If you like Fuel, you might also like other libraries of mine;
Result - The modelling for success/failure of operations in Kotlin
Fuse - A simple generic LRU memory/disk cache for Android written in Kotlin
Forge - Functional style JSON parsing written in Kotlin
ReactiveAndroid - Reactive events and properties with RxJava for Android SDK
Credits
Fuel is brought to you by contributors.
Licenses
Fuel is released under the MIT license.
Last updated
Was this helpful?