Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class AppRestService : IAppRestService {
override fun getAppRestService(): IRestService {
val httpClient = OkHttpClient().newBuilder()
val interceptor = Interceptor { chain ->
val request = chain?.request()?.newBuilder()?.addHeader("SomeHeader", "SomeHeaderProperty")?.build();
chain?.proceed(request)
}
httpClient.networkInterceptors().add(interceptor)
val customGson = GsonBuilder().registerTypeAdapter(MyClassCloud::class.java, MyClassCloudDeserializer("1")).create()
val retrofit = Retrofit.Builder().baseUrl(IRestService.URL_BASE).addConverterFactory(GsonConverterFactory.create(customGson)).client(httpClient.build()).build()
val scondoo = retrofit.create(IRestService::class.java)
return scondoo
}
}
class MyClassCloudDeserializer(val id: Int) : JsonDeserializer<MyClassCloud> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): MyClassCloud? {
val root = json?.asJsonObject?.get("items")?.asJsonObject;
val jsonStr = root?.get(id.toString())?.asJsonObject
val article = Gson().fromJson(jsonStr, MyClassCloud::class.java)
return article
}
}
class MyClassRestService {
@Throws(IOException::class)
fun getMyClass(): MyClassCloud {
val call = AppRestService().getAppRestService().getMyClass()
val execution = call.execute()
if (execution.isSuccessful) {
return execution.body()
} else {
throw HttpException(execution.code(), execution.errorBody().string())
}
}
}
IRestService : {
@GET("<URL_TO_GET_MY_CLASS>")
fun getMyClass(): Call<MyClassCloud>
}
//{
// "items": {
// "452217": {
// "id": 452217,
// "title": "Title"
// }
// }
// }
@phileo

This comment has been minimized.

Copy link

commented Jan 8, 2018

@HugoMatilla
Interceptor.intercept() throws IOException.
How can I handle the IOException?
Is the only option to add a try-catch inside the intercept() function, or are there any better alternatives?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.