Created
December 18, 2017 18:10
-
-
Save Audhil/dcfa785985c1d93b440c8ba74e5f3330 to your computer and use it in GitHub Desktop.
How to fake a network response with Retrofit2?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// step 1 - make a fake response interceptor | |
class FakeResponseInterceptor : Interceptor { | |
@Throws(IOException::class) | |
override fun intercept(chain: Interceptor.Chain): Response? { | |
val responseString = "{\n" + | |
"\t\"name\": \"audhil\",\n" + | |
"\t\"occupation\": \"android developer\"\n" + | |
"}" | |
var response: Response? = null | |
response = Response.Builder() | |
.code(200) | |
.message(responseString) | |
.request(chain.request()) | |
.protocol(Protocol.HTTP_1_0) | |
.body(ResponseBody.create(MediaType.parse("application/json"), responseString.toByteArray())) | |
// .addHeader("content-type", "application/json") | |
.build() | |
return response | |
} | |
} | |
// step 2 - make a OkHttpClient | |
private fun getHttpClientWithInterceptors(): OkHttpClient { | |
val httpClient = OkHttpClient.Builder() | |
httpClient.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) | |
httpClient.interceptors().add(FakeResponseInterceptor()) | |
return httpClient.build() | |
} | |
// step 3 - add OkHttpClient in Retrofit2 | |
private val retrofit = Retrofit.Builder() | |
.baseUrl(".....") | |
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create())) | |
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) | |
.client(getHttpClientWithInterceptors()) | |
.build() | |
var service = retrofit.create(APIService::class.java) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment