Hot questions for Handling SocketTimeOutException in Retrofit

Top 10 Java Open Source / Retrofit / Handling SocketTimeOutException

Retrofit SocketTimeOutException in sending multiparty or JSON data in android

Question: Facing problem in sending a Mutipart or JSON data through retrofit lib

Retrofit Interface

@Multipart
@POST("/api/v1/protected/updateprofile")
void uploadPhoto(@Part("name") String name,
                 @Part("image") TypedFile file,
                 Callback<ApiResponseModel> callback);

Adapter Code

private RestApi restApi;
RestAdapter restAdapter = new RestAdapter.Builder().setClient(new OkClient(getClient())).setConverter(new GsonConverter(gson)).setRequestInterceptor(interceptor).setLogLevel(RestAdapter.LogLevel.FULL).setEndpoint(Config.baseUrl).build();
        restApi = restAdapter.create(RestApi.class);

Error Log Generated after sending JSON request

 java.io.InterruptedIOException: timeout
            at okio.AsyncTimeout.exit(AsyncTimeout.java:258)
            at okio.AsyncTimeout$2.read(AsyncTimeout.java:215)
            at okio.RealBufferedSource.indexOf(RealBufferedSource.java:206)
            at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:153)
            at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:189)
            at com.squareup.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:101)
            at com.squareup.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:676)
            at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:426)
            at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:371)
            at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:466)
            at retrofit.client.UrlConnectionClient.readResponse(UrlConnectionClient.java:73)
            at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:38)
            at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:321)
            at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
            at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)
            at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)

I have tried to increase the timeout of the request in Request Adapter

  private OkHttpClient getClient() {
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(30, TimeUnit.SECONDS);
        client.setReadTimeout(30, TimeUnit.SECONDS);
        return client;
    }

Answer: I have this error a few days ago and I discovered that your solution is correct but add more time

private OkHttpClient getClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(5, TimeUnit.MINUTES);
    client.setReadTimeout(5, TimeUnit.MINUTES);
    return client;
}

For OkHttp3

 private OkHttpClient getClient() {
    OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(5, TimeUnit.MINUTES)
    .readTimeout(5, TimeUnit.MINUTES)
    .build();
    return client;
}

Retrofit SocketTimeoutException (and/or http 500 error) on http-POST

Question: I'm trying to do a POST request to our backend server, but I keep getting SocketTimeOutExceptions or HTTP 500 error. And it keeps switching between those two randomly (even with the same values).

Things I've already tried

  1. adding OkHttp library (v2.4.0) for some reason I get the error that it's might not be supported though retrofit says it supports v2.0.0+ source
  2. implementing Callback<Account> into the class instead of this, it also gave me the http500 more than the newer version/li>
  3. I've added the UrlFactory and OkHttp libraries and followed these steps but then the entire app crashes

SignIn code

public class SignIn extends Activity implements Callback<Account>{
    private static final String TAG = "SignIn";
    private ImageButton sign_in_backBtn;
    private TextView sign_in_make_account;
    private Button btn_SignIn;
    private EditText email;
    private EditText password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_in);

        btn_SignIn = (Button) findViewById(R.id.sign_in_btnSignIn);
        email = (EditText)findViewById(R.id.sign_in_email);
        password = (EditText)findViewById(R.id.sign_in_password);
        initListers();
    }

    private void initListers() {
        btn_SignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String emailAdres = email.getText().toString();
                String passWord = password .getText().toString();
                if(emailAdresValidate == true && passWordValidate == true){
                    Account account = new Account(passWord,emailAdres);
                    login(account);
                }
            }
        });
    }

    private void login(Account account){
        JppApplication.getService().logIn(account,this);
    }

    @Override
    public void success(Account account, Response response) {
        Log.d(TAG,response.toString());
        Log.d(TAG, "login success");
    }

    @Override
    public void failure(RetrofitError retrofitError) {
        Log.e(TAG,retrofitError.getKind().toString());
        Log.d(TAG, "login failed");
    }
}

Service code

public interface Service {
    @POST("/accounts/login")
    void logIn(@Body Account account,Callback<Account> created);
}

Account

public class Account {
    @SerializedName("Email")
    private String email;

    @SerializedName("Password")
    private String paswoord;

    public Account(String paswoord, String email) {
        this.paswoord = paswoord;
        this.email = email;
    }
}

Answer: Ok so turns out the error was because of the following. Our school used a cheap VPN where the server was running on. I always tested this app by running and debugging it on a physical device instead of running it on an emulator.

You had to use the VPN's app to be able to connect to the server, for some reason the connection went down regularly, so whenever we had a timeout exception we just had to restart the VPN connection through the app and we were sure to not receive any timeout exceptions for about a minute or so.

This is what you get when schools try to cut budgets everywhere.

And of course the HTTP-500 was because of an error in our code obviously


Retrofit SocketTimeoutException - Uploading Image

Question: I'm currently using Retrofit for Android as my network communications. When POSTing to my backend server an image, the server is in the middle of the upload and then retrofit "times out" with SocketTimeoutException.

I have added the OKhttp library as some have suggested and still getting the timeout.

The current img sizes are around 750kb because I have scaled them down.

Is there an appropriate way to changes the amount of time until a timeout for retrofit? Or is there a better way to upload images to a server?

Answer: Perhaps try changing the timeout with setReadTimeout on your OkHttpClient; note that a setting of 0 indicates to never time out.

Bonus: if you need help figuring out an appropriate setting, you can read the bytes successfully transferred before the timeout from the exception, and also find out the current default read timeout with getReadTimeout.