retrofit2: java.io.EOFException even when Postman works fine

776 Views Asked by At

I'm trying to retrieve data from an API using an endpoint that works on Postman. However, when I use it on Retrofit I get the EOFException. (using also interceptor to add a bearer token)

MyInterface:

   interface ITerminalAPIService {

    @GET("api/users/{UserId}")
    fun getUser(@Path("UserId")userId: Long): Call<User>

myApi Provider:

fun getRetrofitUser(context: Context, userId:Long) {
    val usersRetrofit = getRetrofit(context)
    val usersApiService = usersRetrofit.create(ITerminalAPIService::class.java)
    try {
        val apiUsers = usersApiService.getUser(userId)

        apiUsers.enqueue(object : Callback<User> {
            override fun onResponse(
                call: Call<User>,
                response: Response<User>
            ) {
                if (!response.isSuccessful) {
                    println("user response unsuccessful: ${response.code()}")
                }
                val user = response.body()
                /** do something with user*/

            override fun onFailure(call: Call<User>, t: Throwable) {
                t.printStackTrace()
            }
        })

    } catch (e: Exception) {
        e.printStackTrace()
    }
}


private fun getRetrofit(context: Context): Retrofit {
    val logInterceptor = HttpLoggingInterceptor()
    logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    return Retrofit.Builder().baseUrl(BACKEND_URL)
        .client(
            OkHttpClient().newBuilder()
                .connectTimeout(120, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .addInterceptor(AuthInterceptor(context))
                .addInterceptor(logInterceptor)
                .build()
        )
        .addConverterFactory(GsonConverterFactory.create()).build()
}

my intercept class:

class AuthInterceptor(private val context: Context) : Interceptor {

override fun intercept(chain: Interceptor.Chain): Response {
    var token: String? = null
    runBlocking {
        token = context.getSharedPreferences("Authenticate", Context.MODE_PRIVATE)
            .getString("Authenticate", "")
    }

    val newRequest = chain.request().newBuilder()
        .header("Authorization", "Bearer $token")
        .header("Cache-Control", "no-cache")
        .header("Accept-Encoding", "gzip, deflate")
        .build()

    val response = chain.proceed(newRequest)

    if (response.code in 401..504) {
        //obtain additional data from response
        println("intercept ${response.code} code")
        println("intercept message: " + response.message)
        println("intercept Body: " + response.body)
    }
    return response
}

}

here is the result:

I/okhttp.OkHttpClient: --> GET http://.../api/users/39365
    Authorization: Bearer eyJhb...
I/okhttp.OkHttpClient: Cache-Control: no-cache
    Accept-Encoding: gzip, deflate
    --> END GET
I/okhttp.OkHttpClient: <-- 200 OK http://.../api/users/39365 (268ms)
    Date: Thu, 17 Dec 2020 18:14:02 GMT
    Content-Type: application/json; charset=utf-8
    Server: Kestrel
I/okhttp.OkHttpClient: Transfer-Encoding: chunked

W/System.err: java.io.EOFException
        at okio.RealBufferedSource.require(RealBufferedSource.kt:201)
W/System.err:     at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:400)
        at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:429)
        at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:408)
        at okhttp3.internal.connection.Exchange$ResponseBodySource.read(Exchange.kt:276)
        at okio.RealBufferedSource.request(RealBufferedSource.kt:207)
        at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.kt:245)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at pt.axians.ticketinspector.apicalls.interceptor.AuthInterceptor.intercept(AuthInterceptor.kt:26)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
        at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:502)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)

Consulting retrofit issues, I came across the following link: https://github.com/square/retrofit/issues/2405 . However I do think that there might be a different issue because the endpoint works fine on Postman.

From Postman: enter image description here

enter image description here

Response Headers

0

There are 0 best solutions below