Skip to content Skip to sidebar Skip to footer

Okhttp3 Request Returning Empty Response As Well As Different Headers Than Postman

I'm trying to parse the JSON from this URL, https://fantasy.premierleague.com/drf/elements but the response I get from okhttp and Postman are different. I've also used online API t

Solution 1:

Your problem is User-Agent header. Here is a working example:

fun syncGetOkHttp() {
    println("\n===")
    println("OkHttp")
    println("===")
    val client = OkHttpClient().newBuilder()
            .addNetworkInterceptor { chain ->
                val (request, response) = chain.request().let {
                    Pair(it, chain.proceed(it))
                }

                println("--> ${RequestLine.get(request, Proxy.Type.HTTP)})")
                println("Headers: (${request.headers().size()})")
                request.headers().toMultimap().forEach { k, v -> println("$k : $v") }

                println("<-- ${response.code()} (${request.url()})")

                val body = if (response.body() != null)
                    GZIPInputStream(response.body()!!.byteStream()).use {
                        it.readBytes(50000)
                    } else null

                println("Response: ${StatusLine.get(response)}")
                println("Length: (${body?.size ?: 0})")

                println("""Body: ${if (body != null && body.isNotEmpty()) String(body) else "(empty)"}""")
                println("Headers: (${response.headers().size()})")
                response.headers().toMultimap().forEach { k, v -> println("$k : $v") }

                response
            }
            .build()

    Request.Builder()
            .url(url)
            .header("Accept", "application/json")
            .header("User-Agent", "Mozilla/5.0")
            .build()
            .let { client.newCall(it).execute() }
}

Post a Comment for "Okhttp3 Request Returning Empty Response As Well As Different Headers Than Postman"