Created
January 7, 2025 12:29
-
-
Save OhhhThatVarun/a6782baebe395b9ffa7368ed27922bd1 to your computer and use it in GitHub Desktop.
A Retrofit Interceptor for logging network requests as cURL commands in Android
This file contains 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
import okhttp3.Interceptor | |
import okhttp3.Request | |
import okhttp3.Response | |
import java.io.IOException | |
/** | |
* A Retrofit Interceptor for logging network requests as cURL commands in Android. | |
*/ | |
class CurlLoggingInterceptor : Interceptor { | |
@Throws(IOException::class) | |
override fun intercept(chain: Interceptor.Chain): Response { | |
val request = chain.request() | |
val curlCommand = buildCurlCommand(request) | |
// Log the cURL command to the console | |
println("CURL: $curlCommand") | |
return chain.proceed(request) | |
} | |
private fun buildCurlCommand(request: Request): String { | |
val curlCommand = StringBuilder("curl -X ${request.method}") | |
// Add headers | |
for ((name, value) in request.headers) { | |
curlCommand.append(" -H \"$name: $value\"") | |
} | |
// Add body if present | |
request.body?.let { body -> | |
val buffer = okio.Buffer() | |
body.writeTo(buffer) | |
val bodyString = buffer.readUtf8() | |
curlCommand.append(" -d '${bodyString.replace("'", "\\'")}'") | |
} | |
// Add URL | |
curlCommand.append(" \"${request.url}\"") | |
return curlCommand.toString() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment