Skip to content

Instantly share code, notes, and snippets.

View RoRoche's full-sized avatar

Romain Rochegude RoRoche

View GitHub Profile
@RoRoche
RoRoche / build_okhttp3.gradle
Created November 6, 2019 12:46
build.gradle for OkHttp3 dependency
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.2.2'
import okhttp3.Call
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
class GetReposRequest(private val call: Call) : RestRequest {
constructor(client: OkHttpClient, baseUrl: String, user: String) : this(
client,
interface Repo {
fun id(): Long
fun name(): String
fun description(): String
fun url(): String
}
import org.json.JSONObject
class JsonRepo(private val jsonObject: JSONObject) : Repo {
override fun id(): Long = jsonObject.getLong("id")
override fun name(): String = jsonObject.getString("name")
override fun description(): String = jsonObject.getString("description")
D/GetReposRequest: response - started
D/GetReposRequest: response - done with Response{protocol=http/1.1, code=200, message=OK, url=https://api.github.com/users/RoRoche/repos}
class NoBodyRestResponseException : RuntimeException()
@RoRoche
RoRoche / RestRequest.kt
Last active November 19, 2019 18:05
Kotlin interface for RestRequest
import okhttp3.Response
interface RestRequest {
fun response(): Response
fun cancel()
abstract class Wrap protected constructor(
protected val origin: RestRequest
) : RestRequest by origin
import android.util.Log
import okhttp3.Response
class LoggableRequest(
origin: RestRequest,
private val tag: String = origin.javaClass.simpleName
) : RestRequest.Wrap(origin) {
override fun response(): Response {
Log.d(tag, "response - started")
val response = super.response()
import okhttp3.Response
class WithBodyRestRequest(origin: RestRequest) : RestRequest.Wrap(origin) {
override fun response(): Response {
val response = super.response()
if (response.body != null) {
return response
} else {
throw NoBodyRestResponseException()
}
import okhttp3.Response
class SuccessfulRestRequest(origin: RestRequest) : RestRequest.Wrap(origin) {
override fun response(): Response {
val response = super.response()
if (response.isSuccessful) {
return response
} else {
throw RestRequestFailureException(response)
}