Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save HugoMatilla/a64ccb27735343a33fcbdce2cea41c51 to your computer and use it in GitHub Desktop.
Save HugoMatilla/a64ccb27735343a33fcbdce2cea41c51 to your computer and use it in GitHub Desktop.
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
Copy link

phileo 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