Skip to content

Instantly share code, notes, and snippets.

@Nilzor
Last active June 19, 2020 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nilzor/dc4a493355226bfbf86c24feb467d1a6 to your computer and use it in GitHub Desktop.
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
/**
* 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