Skip to content
forked from kittinunf/fuel

The easiest HTTP networking library in Kotlin for Android

Notifications You must be signed in to change notification settings

RenanLukas/Fuel

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Fuel

Kotlin jcenter Build Status

The easiest HTTP networking library in Kotlin for Android.

Features

  • Support basic HTTP GET/POST/PUT/DELETE in a fluent style interface
  • Download file
  • Upload file (multipart/form-data)
  • Configuration manager
  • Debug log / cUrl log
  • Support response deserialization into plain old object (both Kotlin & Java)
  • Automatically invoke handler on Android Main Thread

Installation

Gradle

buildscript {
    repositories {
        jcenter()
    }
}

dependencies {
    compile 'fuel:fuel:0.57'
}

Sample

  • There are two samples, one is in Kotlin and another one in Java.

Quick Glance Usage

  • Kotlin
//an extension over string (support GET, PUT, POST, DELETE with httpGet(), httpPut(), httpPost(), httpDelete())
"http://httpbin.org/get".httpGet().responseString { request, response, either ->
	//do something with response
	when (either) {
	    is Left -> // left means failure
	    is Right -> // right means success
	}
}

//if we set baseURL beforehand, simply use relativePath
Manager.instance.basePath = "http://httpbin.org"
"/get".httpGet().responseString { request, response, either ->    
    //make a GET to http://httpbin.org/get and do something with response
    val (error, data) = either
    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("http://httpbin.org/get").responseString { request, response, either ->
	//do something with response
	either.fold({ error ->
	    //do something with error
	}, { data ->
	    //do something with data
	})
}
  • Java
//get
Fuel.get("http://httpbin.org/get", params).responseString(new Handler<String>() {
    @Override
    public void failure(Request request, Response response, FuelError error) {
    	//do something when it is failure
    }

    @Override
    public void success(Request request, Response response, String data) {
    	//do something when it is successful
    }
});

Detail Usage

GET

Fuel.get("http://httpbin.org/get").response { request, response, either ->
    println(request)
    println(response)
    val (error, bytes) = either
    if (bytes != null) {
        println(bytes)
    }
}

Response Handling

Either

  • Either is a functional style data structure that represents data that contains either left or right but not both. It represents the result of an action that can be error or success (with result). The common functional convention is that the left of an Either class contains an exception (if any), and the right contains the result.

  • Working with either is easy. You could fold, muliple declare as because it is just a data class or do a simple when checking whether it is left or right.

Response

fun response(handler: (Request, Response, Either<FuelError, ByteArray>) -> Unit)

Response in String

fun responseString(handler: (Request, Response, Either<FuelError, String>) -> Unit)

Response in JSONObject

fun responseJson(handler: (Request, Response, Either<FuelError, JSONObject>) -> Unit)

Response in T (object)

fun <T> responseObject(deserializer: ResponseDeserializable<T>, handler: (Request, Response, Either<FuelError, T>) -> Unit)

POST

Fuel.post("http://httpbin.org/post").response { request, response, either ->
}

//if you have body to post it manually
Fuel.post("http://httpbin.org/post").body("{ \"foo\" : \"bar\" }").response { request, response, either ->
}

PUT

Fuel.put("http://httpbin.org/put").response { request, response, either ->
}

DELETE

Fuel.delete("http://httpbin.org/delete").response { request, response, either ->
}

Debug Logging

  • Use toString() method to Log (request|response)
Log.d("log", request.toString())
//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
Log.d("cUrl log", request.cUrlString())
//print
curl -i -X POST -d "foo=foo&bar=bar&key=value" -H "Accept-Encoding:compress;q=0.5, gzip;q=1.0" -H "Device:Android" -H "Content-Type:application/x-www-form-urlencoded" "http://httpbin.org/post"

Parameter Support

  • URL encoded style for GET & DELETE request
Fuel.get("http://httpbin.org/get", listOf("foo" to "foo", "bar" to "bar")).response { request, response, either -> {
    //resolve to http://httpbin.org/get?foo=foo&bar=bar
}

Fuel.delete("http://httpbin.org/delete", listOf("foo" to "foo", "bar" to "bar")).response { request, response, either ->
    //resolve to http://httpbin.org/get?foo=foo&bar=bar
}
  • Support x-www-form-urlencoded for PUT & POST
Fuel.post("http://httpbin.org/post", listOf("foo" to "foo", "bar" to "bar")).response { request, response, either ->
    //http body includes foo=foo&bar=bar
}

Fuel.put("http://httpbin.org/put", listOf("foo" to "foo", "bar" to "bar")).response { request, response, either ->
    //http body includes foo=foo&bar=bar
}

Download with or without progress handler

Fuel.download("http://httpbin.org/bytes/32768").destination { response, url ->
    File.createTempFile("temp", ".tmp")
}.response { req, res, either -> {

}

Fuel.download("http://httpbin.org/bytes/32768").destination { response, url ->
    File.createTempFile("temp", ".tmp")
}.progress { readBytes, totalBytes ->
    val progress = readBytes.toFloat() / totalBytes.toFloat()
}.response { req, res, either -> {

}

Upload with or without progress handler

Fuel.upload("/post").source { request, url ->
    File.createTempFile("temp", ".tmp");
}.responseString { request, response, either ->

}

Authentication

  • Support Basic Authentication right off the box
val username = "username"
val password = "abcd1234"

Fuel.get("http://httpbin.org/basic-auth/$user/$password").authenticate(username, password).response { request, response, either ->
}

Validation

  • By default, the valid range for HTTP status code will be (200..299). However, it can be configurable
Fuel.get("http://httpbin.org/status/418").response { request, response, either ->
    //either contains Error

}

//418 will pass the validator
Fuel.get("http://httpbin.org/status/418").validate(400..499).response { request, response, either ->
    //either contains data
}

Advanced Configuration

Response Deserialization

  • Fuel provides built-in support for response deserialization. Here is how one might want to use Fuel together with Gson
//User Model
data class User(val firstName: String = "",
                val lastName: String = "") {

    //User Deserializer
    class Deserializer : ResponseDeserializable<User> {
        override fun deserialize(content: String) = Gson().fromJson(content, User::class.java)
    }

}

//Use httpGet extension
"http://www.example.com/user/1".httpGet().responseObject(User.Deserializer()) { req, res, either
    //either is of type Either<Exception, User>
    val (err, user) = either

    println(user.firstName)
    println(user.lastName)
}
  • 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.
public fun deserialize(bytes: ByteArray): T?

public fun deserialize(inputStream: InputStream): T?

public fun deserialize(reader: Reader): T?

public fun deserialize(content: String): T?
  • Another example may be parsing a website that is not UTF-8. Since Fuel by default serialize text as UTF-8, we need to define our deserializer:
object Windows1255StringDeserializer : ResponseDeserializable<String> {
        override fun deserialize(bytes: ByteArray): String {
            return String(bytes, "windows-1255")
        }
    }

Configuration

  • Use singleton Manager.instance to manager global configuration.

  • basePath is used to manage common root path. Great usage is for your static API endpoint.

Manager.instance.basePath = "https://httpbin.org
Fuel.get("/get").response { request, response, either ->
    //make request to https://httpbin.org/get because Fuel.{get|post|put|delete} use Manager.instance to make HTTP request
}
  • baseHeaders is to manage common HTTP header pairs in format of Map<String, String>>.
Manager.instance.baseHeaders = mapOf("Device" to "Android")
Fuel.get("/get").response { request, response, either ->
    //make request to https://httpbin.org/get with global device header (Device : Android)
}
  • baseParams is used to manage common key=value query param, which will be automatically included in all of your subsequent requests in format of List<Pair<String, Any?>> (Any is converted to String by toString() method)
Manager.instance.baseParams = listOf("api_key" to "1234567890")
Fuel.get("/get").response { request, response, either ->
    //make request to https://httpbin.org/get?api_key=1234567890
}
  • client is a raw HTTP client driver. Generally, it is responsible to make Request into Response. Default is HttpClient which is a thin wrapper over java.net.HttpUrlConnnection. You could use any httpClient of your choice by conforming to client protocol, and set back to Manager.instance to kick off the effect.

Credits

Fuel is brought to you by contributors.

License

Fuel is released under the MIT license.

The MIT License (MIT)

Copyright (c) 2015 by Fuel contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

The easiest HTTP networking library in Kotlin for Android

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Kotlin 94.4%
  • Java 5.6%