SocketTimeoutException in Retrofit

走远了吗. 提交于 2019-11-28 08:54:49

Increase the time if the fetching is taking more time use this code it worked for me

 OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(100, TimeUnit.SECONDS)
            .readTimeout(100,TimeUnit.SECONDS).build();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("yourbaseurl").client(client)
            .addConverterFactory(GsonConverterFactory.create(new  Gson())).build();

hay this is work around not the best practice this comments down Back end should not take this long and user must be notified with error or try again message

Soham

Preventing SocketTimeoutException is beyond our limit...One way to effectively handle it is to define a connection timeout

Example for

retrofit 1.9.0

restadapter = new RestAdapter.Builder().setEndpoint(HOST).setLogLevel(RestAdapter.LogLevel.FULL).setClient(new OkHttpClient()
                .setReadTimeout(30, TimeUnit.SECONDS)
                .setConnectTimeout(30, TimeUnit.SECONDS)).build();

retrofit 2.0.0

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(10, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();

retrofit 2.4.0

// setting custom timeouts
    OkHttpClient.Builder client = new Builder();
    client.connectTimeout(15, TimeUnit.SECONDS);
    client.readTimeout(15, TimeUnit.SECONDS);
    client.writeTimeout(15, TimeUnit.SECONDS);

    if (retrofit == null) {
      retrofit = new Retrofit.Builder()
          .baseUrl(BASE_URL)
          .addConverterFactory(GsonConverterFactory.create())
          .client(client.build())
          .build();
    }
    return retrofit;
  }

A possible resolution for this is make sure that you sending the correct request body to the server. For example, does the server need x-www-form-urlencoded or form-data in its request body? A simple way to test this is using Postman.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!