Search code examples
androidrobospice

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...


Solution

  • 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);
        }
    }