0wl
0wl

Reputation: 876

How to "dump" request body?

Is there any way to get request in the raw representation? I need something like this:

POST /user HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 0
Content-Type: application/json
Host: localhost:8080
User-Agent: okhttp/4.9.0

Upvotes: 1

Views: 652

Answers (2)

0wl
0wl

Reputation: 876

I ended up with a following strange solution in my interceptor:

val buffer = okio.Buffer()
request.body?.writeTo(buffer)

    val rawRequest = buildString {
        append("${request.method} ${chain.request().url.encodedPath} ${chain.connection()?.protocol().toString().toUpperCase()}\n")
        append(chain.request().headers.map { "${it.first}: ${it.second}\n" }.reduce { acc, s -> "$acc$s" })
        append(buffer.readString(Charsets.UTF_8))
    }
    
    
    Log.e("RAW request", "$rawRequest")

One important thing: You have to use networkInterceptor

Upvotes: 0

Jesse Wilson
Jesse Wilson

Reputation: 40613

Try the built in logging interceptor or write your own.

Or try Chucker if you're on Android.

Upvotes: 1

Related Questions