Skip to content

Instantly share code, notes, and snippets.

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 gianpaolof/11ba07016f77f676e6df0b2725686305 to your computer and use it in GitHub Desktop.
Save gianpaolof/11ba07016f77f676e6df0b2725686305 to your computer and use it in GitHub Desktop.
Android : Mock Response with Retrofit & OkHttp
class LoginInterceptor: Interceptor{
override fun intercept(chain: Interceptor.Chain): Response {
//If requested endpoint matched to targeted endpoint, we will return an mocked response.
if (chain.request().url.toUri().toString().endsWith("fake-login")) {
val responseString = "OUR_JSON_RESPONSE_FROM_ASSET_OR_OTHER_SOURCE"
return chain.proceed(chain.request())
.newBuilder()
.code(200)
.protocol(Protocol.HTTP_2)
.message(responseString)
.body(
responseString
.toByteArray()
.toResponseBody(
"application/json".toMediaTypeOrNull()
)
)
.addHeader("content-type", "application/json")
.build()
} else {
//Skip the interception.
return chain.proceed(chain.request())
}
}
}
object RetrofitProvider {
//Return a lazy instance of OkHttp client
private val myHttpClient: OkHttpClient by lazy {
val ins = OkHttpClient().newBuilder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.retryOnConnectionFailure(true)
//Adding our LoginInterceptor only on Debug mode only
if (BuildConfig.DEBUG){
ins.addInterceptor(LoginInterceptor())
}
ins.build()
}
//Public access point for Mock API Service
fun getMockAPI(): MockAPIEndpoint = retrofitInstance.create(MockAPIEndpoint::class.java)
//Return a lazy Retrofit instance
private val retrofitInstance: Retrofit by lazy {
Retrofit.Builder()
.baseUrl("https://rommansabbir/api/v2/")
.client(myHttpClient)
.build()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment