Last active
March 14, 2024 21:49
-
-
Save HugoMatilla/a64ccb27735343a33fcbdce2cea41c51 to your computer and use it in GitHub Desktop.
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
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" | |
// } | |
// } | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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?