Skip to content

Instantly share code, notes, and snippets.

@rajsingha
Last active February 15, 2023 10:48
Show Gist options
  • Save rajsingha/a270bfba39e9b3728d0bd60d55cb23d0 to your computer and use it in GitHub Desktop.
Save rajsingha/a270bfba39e9b3728d0bd60d55cb23d0 to your computer and use it in GitHub Desktop.
Android - Forward Proxy Adapter
package com.example.app.network
import android.content.Context
import android.util.Log
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.IOException
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.net.URI
import java.util.*
class ForwardProxyInterceptor(context: Context) : Interceptor {
private val mContext: Context
private var mContentType = "application/json"
init {
mContext = context
}
/**
* Set content type for header
* @param contentType Content type
* @return ForwardProxyInterceptor
*/
fun setContentType(contentType: String): FakeInterceptor {
mContentType = contentType
return this
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val listSuggestionFileName: MutableList<String> = ArrayList()
val method: String = chain.request().method.lowercase(Locale.ROOT)
var response: Response? = null
// Get Request URI.
val uri: URI = chain.request().url.toUri()
Log.d(
TAG,
"--> Request url: [" + method.uppercase(Locale.getDefault()) + "]" + uri.toString()
)
val defaultFileName = getFileName(chain)
//create file name with http method
//eg: getLogin.json
listSuggestionFileName.add(method + upCaseFirstLetter(defaultFileName))
//eg: login.json
listSuggestionFileName.add(defaultFileName)
val responseFileName = getFirstFileNameExist(listSuggestionFileName, uri)
if (responseFileName != null) {
val fileName = getFilePath(uri, responseFileName)
Log.d(TAG, "Read data from file: $fileName")
try {
val `is`: InputStream = mContext.assets.open(fileName)
val r = BufferedReader(InputStreamReader(`is`))
val responseStringBuilder = StringBuilder()
var line: String?
while (r.readLine().also { line = it } != null) {
responseStringBuilder.append(line).append('\n')
}
Log.d(TAG, "Response: $responseStringBuilder")
response = Response.Builder()
.code(200)
.message(responseStringBuilder.toString())
.request(chain.request())
.protocol(Protocol.HTTP_1_0)
.body(
responseStringBuilder.toString().toByteArray()
.toResponseBody(mContentType.toMediaTypeOrNull())
)
.addHeader("content-type", mContentType)
.build()
} catch (e: IOException) {
Log.e(TAG, e.message, e)
}
} else {
for (file in listSuggestionFileName) {
Log.e(TAG, "File not exist: " + getFilePath(uri, file))
}
response = chain.proceed(chain.request())
}
Log.d(TAG, "<-- END [" + method.uppercase(Locale.getDefault()) + "]" + uri.toString())
return response!!
}
private fun upCaseFirstLetter(str: String): String {
return str.substring(0, 1).uppercase(Locale.getDefault()) + str.substring(1)
}
@Throws(IOException::class)
private fun getFirstFileNameExist(inputFileNames: List<String>, uri: URI): String? {
var mockDataPath: String = uri.host + uri.path
mockDataPath = mockDataPath.substring(0, mockDataPath.lastIndexOf('/'))
Log.d(TAG, "Scan files in: $mockDataPath")
//List all files in folder
val files: Array<String> = mContext.assets.list(mockDataPath) as Array<String>
for (fileName in inputFileNames) {
for (file in files) {
if (fileName == file) {
return fileName
}
}
}
return null
}
private fun getFileName(chain: Interceptor.Chain): String {
val fileName: String =
chain.request().url.pathSegments[chain.request().url.pathSegments.size - 1]
return if (fileName.isEmpty()) "index$FILE_EXTENSION" else fileName + FILE_EXTENSION
}
private fun getFilePath(uri: URI, fileName: String): String {
val path: String = if (uri.path.lastIndexOf('/') !== uri.path.length - 1) {
uri.path.substring(0, uri.path.lastIndexOf('/') + 1)
} else {
uri.path
}
return uri.host + path + fileName
}
companion object {
private val TAG = FakeInterceptor::class.java.simpleName
private const val FILE_EXTENSION = ".json"
}
}
@rajsingha
Copy link
Author

Forward Proxy drawio (4)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment