How to get body string from RequestBody in kotlin?

Viewed 2389

I want to get a body string from the object instance of okhttp3.RequestBody. Can anyone help?

2 Answers

A RequestBody's content can be written out using the following method:

writeTo(okio.BufferedSink sink)

Okio also has a Buffer type which is both a BufferedSink (meaning you can write to it) and a BufferedSource (meaning you can read from it).

Thus, we can write the body to a Buffer and then read it back as a string.

val body = ...
val buffer = Buffer()
body.writeTo(buffer)
val bodyString = buffer.readUtf8()

(to complement @Jake's nice answer with a full example)

Here you can see how you could add a header with the signature of the request body:

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer

class MyInterceptor(
    private val signer: Sha256Signer
) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        return chain.proceed(
            chain.request().newBuilder()
                .addContentTypeHeader()
                .addUserAgentHeader()
                .addBunqHeaders(chain.request())
                .build()
        )
    }

    // ...

    private fun Request.Builder.addSignatureHeader(request: Request) =
        header("X-Client-Signature", signer.sign(request.getBodyAsString()))

    private fun Request.getBodyAsString(): String {
        val requestCopy = this.newBuilder().build()
        val buffer = Buffer()
        requestCopy.body?.writeTo(buffer)
        return buffer.readUtf8()
    }
}
Related