-
Notifications
You must be signed in to change notification settings - Fork 431
Quick Glance Usage
Alvaro Garcia edited this page Mar 6, 2018
·
2 revisions
- Kotlin
//an extension over string (support GET, PUT, POST, DELETE with httpGet(), httpPut(), httpPost(), httpDelete())
"http://httpbin.org/get".httpGet().responseString { request, response, result ->
//do something with response
when (result) {
is Result.Failure -> {
error = result.getAs()
}
is Result.Success -> {
data = result.getAs()
}
}
}
//if we set baseURL beforehand, simply use relativePath
FuelManager.instance.basePath = "http://httpbin.org"
"/get".httpGet().responseString { request, response, result ->
//make a GET to http://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("http://httpbin.org/get").responseString { request, response, result ->
//do something with response
result.fold({ d ->
//do something with data
}, { err ->
//do something with error
})
}
- 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
}
});
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
val (request, response, result) = "http://httpbin.org/get".httpGet().responseString() // result is Result<String, FuelError>
- Java
try {
Triple<Request, Response, String> data = Fuel.get("http://www.google.com").responseString();
Request request = data.getFirst();
Response response = data.getSecond();
Result<String,FuelError> text = data.getThird();
} catch (Exception networkError) {
}
- Kotlin
val jsonPayload = """
{"username": "johndoe1"}
"""
val httpPost = "/users/"
.httpPost()
.body(jsonPayload, Charsets.UTF_8)
.header("Content-Type" to "application/json")
//... continue working with the request