Giter Site home page Giter Site logo

fuel's Introduction

Fuel

Kotlin jcenter

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.53'
}

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 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 result of action that can be error or success (with result). The common functional convention is the left of an Either class contains an exception (if any), and the right contains the result.

  • Work 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 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, (200..299) status code will be valid range for HTTP status code. However, it can be configurable
Fuel.get("http://httpbin.org/status/418").response { request, response, either -> 
    //either contains Error
    
}

//418 will pass 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, javaClass<User>())
    }

}

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

    println(user.firstName)
    println(user.lastName)
}
  • There are 4 of methods to support response deserialization depending on your needs (also depending on JSON parsing library of your choice), you are required to implement just 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?

Configuration

  • Use singleton Manager.instance to manager global configuration.

  • basePath is 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 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.

fuel's People

Contributors

kittinunf avatar yoavst avatar

Watchers

Michael jentsch avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.