Wednesday, 6 November 2019

Receiving incomplete response from retrofit

I am using retrofit version 2.6.1 for making http request over the network. The JSON i am expecting is 42466 character long. However i am receiving only 4073 character and API are working fine on web broswer and postman.

So i added custom okhttp client and increses timeout but it does not help me.

private var okHttpClient: OkHttpClient = OkHttpClient().newBuilder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .build()

Then i tried adding logging interceptor and i found that okhttp is receiving the reponse what i wanted in interceptor logs but in chunks.

private val httpInterceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
private var okHttpClient: OkHttpClient = OkHttpClient().newBuilder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .addInterceptor(httpInterceptor)
    .build()

At last i assigned http client and interceptor to retrofit builder and this is how its look

private val centralRetrofit = Retrofit.Builder().baseUrl("https://www.********.com/")
    .addConverterFactory(ScalarsConverterFactory.create())
    .client(okHttpClient)
    .build()
    .create(MusicAccess::class.java)

So i think using post request will help me rather than get and tried taking all the response in string format to check the reponse

@Headers("Content-Type: text/html; charset=UTF-8")
@POST("**********")
fun getMusic(): Call<String>

But it also did not get to conclusion after that i thought http response will have size limit and used reader to access the json from url by following way.

val client = OkHttpClient()
val request = Request.Builder().url("********")
    .addHeader("Content-Type", "application/json")
    .build()
val response = client.newCall(request).execute()
val input = response.body()?.byteStream()
val reader = BufferedReader(InputStreamReader(input))

But as this https://stackoverflow.com/a/26023885/7639056 answer state that we cannot configure the OkHttpClient to read more than 2048 bytes from the buffer

So is there any way i can get all the data at once?



from Receiving incomplete response from retrofit

No comments:

Post a Comment