Skip to content

Instantly share code, notes, and snippets.

@AidaIssayeva
Last active March 20, 2020 21:52
Show Gist options
  • Save AidaIssayeva/72b8a5b255765e667dab0d6b5f46149d to your computer and use it in GitHub Desktop.
Save AidaIssayeva/72b8a5b255765e667dab0d6b5f46149d to your computer and use it in GitHub Desktop.
This OkHttp application interceptor reads local json file. The json file name is passed as a path in service
interface CustomService {
@GET("veggies.json")
fun getVeggies(): Single<Response<CustomGenericResponse<List<Veggie>>>>
}
class LocalJsonInterceptor(private val context: Context) : Interceptor {
override fun intercept(chain: Chain): Response {
try {
val pathSegments = chain.request().url.pathSegments
if (pathSegments.isNotEmpty()) {
val scenario = pathSegments.first()
val inputStream = context.assets.open(scenario)
var mimeType = URLConnection.guessContentTypeFromStream(inputStream)
if (mimeType == null) {
mimeType = "application/json"
}
return Response.Builder()
.addHeader("content-type", mimeType)
.body(ResponseBody.create(mimeType.toMediaTypeOrNull(), toByteArray(inputStream)))
.code(200)
.message("Mock response from assets/".plus(scenario))
.protocol(Protocol.HTTP_1_0)
.request(chain.request())
.build()
} else {
throw Exception("no path is found")
}
} catch (e: IOException) {
e.printStackTrace()
throw Exception(e)
}
}
private fun toByteArray(inputStream: InputStream): ByteArray {
val outputStream = ByteArrayOutputStream()
inputStream.use { input ->
outputStream.use { output ->
input.copyTo(output)
}
}
return outputStream.toByteArray()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment