Android Question How to set readTimeout in a OkHttp connection

Jose Cuevas

Member
Licensed User
Longtime User
Hi I am consuming a REST Web Service using an HttpJob and setting the TimeOut to 6 seconds with this command XJob.GetRequest.Timeout = 6000, this timeout is very important, because it is a heavy duty App and if the WebService takes more than 6 seconds, I need to continue with another process .

But I have been told that this Timeout is only for Connection and that OkHttp has timeout for Connection and Read (https://www.baeldung.com/okhttp-timeouts). So when the connection lasts more than 6 seconds, the connection timeout is triggered and everything works fine.

The problem comes when the connection lasts less than 6 seconds, but the WebService response lasts up to 30 seconds, that timeout is controlled by the readTimeout. I found this code in Java, but I don't know Java and how to implement it in B4A:

B4X:
@Test
public void whenReadTimeoutExceeded_thenSocketTimeoutException() {
    OkHttpClient client = new OkHttpClient.Builder()
      .readTimeout(10, TimeUnit.MILLISECONDS)
      .build();

    Request request = new Request.Builder()
      .url("https://httpbin.org/delay/2") // 2-second response time
      .build();

    Throwable thrown = catchThrowable(() -> client.newCall(request).execute());

    assertThat(thrown).isInstanceOf(SocketTimeoutException.class);
}

Is there any way to set the readTimeout from B4A?

I would appreciate any help because I am over my deadline and my client is starting to get upset.

Thanks in advance.
 

Jose Cuevas

Member
Licensed User
Longtime User

Thanks mcqueccu for your response, but the GetRequest.Timeout is just for Connection Timeout, there are 4 Timeouts: Connection, Read, Write and Call, and I need to set the Read and Call TimeOut.

I'm making some tests with this code, and apparently is working. But I need some more tests.

B4X:
Sub OkHttpTimeout
   
    Dim connTimeOut As Long = 5000
    Dim readTimeOut As Long = 2000
    Dim callTimeOut As Long = 2000
    Dim jo As JavaObject = HttpUtils2Service.hc
    Dim builder As JavaObject = jo.RunMethod("sharedInit", Array("hc"))
   
    Dim TimeUnit As JavaObject
    TimeUnit.InitializeStatic("java.util.concurrent.TimeUnit")
    Dim Milliseconds As JavaObject = TimeUnit.GetField("MILLISECONDS")
   
    builder.RunMethod("connectTimeout", Array(connTimeOut, Milliseconds))
    builder.RunMethod("readTimeout", Array(readTimeOut, Milliseconds))
    builder.RunMethod("callTimeout", Array(callTimeOut, Milliseconds))
    jo.SetField("client", builder.RunMethod("build", Null))
   
End Sub
 
Last edited:
Upvote 0
Top