Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Connection TimeOut in RoboSpice request android

I am using RoboSpice for Rest Api calls in android and i want to add connection timeout for 30 secs in calls how i will do ?

here is my code

 public class AddBrandsService extends
        SpringAndroidSpiceRequest<AddBrands.Response> {

     public final AddBrands.Response loadDataFromNetwork(){

     return getRestTemplate().postForObject(url,
            request, AddBrands.Response.class);
    }

    }


    this service is called here 

    private SpiceManager contentManager = new SpiceManager(
        JacksonSpringAndroidSpiceService.class);

    contentManager.execute(service, lastRequestCacheKey,
                DurationInMillis.ONE_SECOND, new AddBrandsListner());

thanks in advance...

like image 540
Zaid Bin Tariq Avatar asked Oct 21 '22 09:10

Zaid Bin Tariq


1 Answers

Here is the code. Basically, you have to take care of the version of android as spring android switch between two different implementations to avoid a known bug in network stack. Unfortunately both implementations don't share a common interface whith respect to timeouts.

private void manageTimeOuts(RestTemplate restTemplate) {
    // set timeout for requests
    ClientHttpRequestFactory factory = restTemplate.getRequestFactory();
    if (factory instanceof HttpComponentsClientHttpRequestFactory) {
        HttpComponentsClientHttpRequestFactory advancedFactory = (HttpComponentsClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(WEBSERVICES_TIMEOUT);
        advancedFactory.setReadTimeout(WEBSERVICES_TIMEOUT);
    } else if (factory instanceof SimpleClientHttpRequestFactory) {
        SimpleClientHttpRequestFactory advancedFactory = (SimpleClientHttpRequestFactory) factory;
        advancedFactory.setConnectTimeout(WEBSERVICES_TIMEOUT);
        advancedFactory.setReadTimeout(WEBSERVICES_TIMEOUT);
    }
}
like image 109
Snicolas Avatar answered Nov 03 '22 22:11

Snicolas