Hot questions for Handling TimeoutException in Retrofit

Top 10 Java Open Source / Retrofit / Handling TimeoutException

Retrofit 2: Catch connection timeout exception

Question: I have the following setup:

final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(5, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(5, TimeUnit.SECONDS);

RestAdapter.Builder builder = new RestAdapter.Builder()
        .setClient(new OkClient(okHttpClient))

I am trying to handle the situation in which my server is down and the user gets a connection timeout exception, this is my logging: failed to connect to / (port 3000) after 5000ms

Is there a way to route this into the retrofit failure method so I can handle it over there?

Answer: For Retrofit 2: Define a listener in your web service instance:

public interface OnConnectionTimeoutListener {
    void onConnectionTimeout();

Add an interceptor to your web service:

public WebServiceClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
    client.interceptors().add(new Interceptor() {
        public Response intercept(Chain chain) throws IOException {
            return onOnIntercept(chain);
    Retrofit retrofit = new Retrofit.Builder()
    webService = retrofit.create(WebService.class);

Enclose your intercep code with try-catch block and notify listener when exception happens:

private Response onOnIntercept(Chain chain) throws IOException {
    try {
        Response response = chain.proceed(chain.request());
        String content = UtilityMethods.convertResponseToString(response);
        Log.d(TAG, lastCalledMethodName + " - " + content);
        return response.newBuilder().body(ResponseBody.create(response.body().contentType(), content)).build();
    catch (SocketTimeoutException exception) {
        if(listener != null)

    return chain.proceed(chain.request());

Android Retrofit Causes Socket Timeout Exception

Question: I am making a POST call to a tomcat server running Struts2 using the retrofit library on an Android device. The POST call fails. The tomcat log shows Socket timeout exception.

The same POST using the exact same headers done via curl does not have any issues. I verified that the data on the wire matches using charles proxy.

Any tips/ideas on debugging this issue.

The post call is as follows

   void getCardOrderList(@Body GetOrderListRequest getOrderListRequest, Callback<GetOrderListResponse> cbGetOrderListResponse);

Answer: Adding Square's OKHTTP library into the libs folder fixed the issue.