Skip to content

Instantly share code, notes, and snippets.

@rcgonzalezf
Created February 7, 2018 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcgonzalezf/4405b645d907e47237f320b23390ca83 to your computer and use it in GitHub Desktop.
Save rcgonzalezf/4405b645d907e47237f320b23390ca83 to your computer and use it in GitHub Desktop.
FuelOkHttpClientForHttpPatch sample using OkHttpClient
package com.rcgonzalezf.example.common.network
import com.github.kittinunf.fuel.core.Client
import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.zip.GZIPInputStream
/**
* Create just to support simple patch operations f
*/
class FuelOkHttpClientForHttpPatch : Client {
override fun executeRequest(request: Request): Response {
val body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
ByteArrayOutputStream().apply {
request.bodyCallback?.invoke(request, this, 0)
}.toByteArray())
val okHttpRequestBuilder = okhttp3.Request
.Builder()
.url(request.url)
.patch(body)
request.headers.entries.map { okHttpRequestBuilder.header(it.key, it.value) }
try {
val okHttpRequest: okhttp3.Request = okHttpRequestBuilder.build()
val okHttpResponse = OkHttpClient().newCall(okHttpRequest).execute()
val responseBody = okHttpResponse.body()
if (responseBody != null) {
val contentEncoding = responseBody.contentType()?.toString() ?: ""
return Response(
url = request.url,
headers = okHttpResponse.headers().toMultimap(),
contentLength = responseBody.contentLength(),
statusCode = okHttpResponse.code(),
responseMessage = okHttpResponse.message(),
dataStream = try {
val stream = responseBody.byteStream()
if (contentEncoding.compareTo("gzip", true) == 0)
GZIPInputStream(stream)
else stream
} catch (exception: IOException) {
try {
responseBody.byteStream().close()
} catch (exception: IOException) {
}
ByteArrayInputStream(ByteArray(0))
}
)
} else {
throw FuelError(Exception("Failed to sign up"), ByteArray(0), Response(request.url))
}
} catch (exception: Exception) {
throw FuelError(exception, ByteArray(0), Response(request.url))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment