Last active
June 19, 2020 12:02
-
-
Save Nilzor/dc4a493355226bfbf86c24feb467d1a6 to your computer and use it in GitHub Desktop.
An OkHttp interceptor allowing you to override Content-Type for POST, PUT and PATCH requests
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
/** | |
* Overrides the HTTP Header Content-Type for POST, PATCH and PUT calls to the given [contentType] | |
*/ | |
class ContentTypeInterceptor(private val contentType: String) : Interceptor { | |
override fun intercept(chain: Interceptor.Chain): Response { | |
val request = chain.request() | |
val chainBuilder = request.newBuilder() | |
request.body()?.let { | |
val newBody = ForwardingRequestbody(it, contentType) | |
when (request.method()) { | |
"POST" -> chainBuilder.post(newBody) | |
"PUT" -> chainBuilder.put(newBody) | |
"PATCH" -> chainBuilder.patch(newBody) | |
else -> { /* NO-OP */ } | |
} | |
} | |
return chain.proceed(chainBuilder.build()) | |
} | |
} | |
class ForwardingRequestbody(private val sourceBody: RequestBody, contentType: String): RequestBody() { | |
private val mediaType = MediaType.get(contentType) | |
override fun contentType(): MediaType = mediaType | |
override fun writeTo(sink: BufferedSink) = sourceBody.writeTo(sink) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment