Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling timeout with AndroidAnnotations (Spring Rest)

Basically, what I'm facing today is the following:

  • Handle Request time out when doing Rest actions.

Seems simple written, but not as easy to code.

This is my implementation so far:

List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add( new NetworkInterceptor() );

tpl.setInterceptors( interceptors );

So now, after setting interceptors, I'd like to set custom timeout configurations for the template.

So I do the following: tpl.getRequestFactory().

This is returning a InterceptingClientHttpRequestFactory instead of SimpleClientHttpRequestFactory as would be returned in case no interceptors were set.

So as it is returning that InterceptingClientHttpRequestFactory instance, I can't set the Timeout.

You can check the sourcecode of Spring, the last method: http://grepcode.com/file_/repo1.maven.org/maven2/org.springframework/spring-web/3.1.1.RELEASE/org/springframework/http/client/support/InterceptingHttpAccessor.java/?v=source

So... Any tips?

like image 318
Reinherd Avatar asked Jan 30 '14 08:01

Reinherd


2 Answers

Assuming tpl is a RestTemplate, you can pass a SimpleClientHttpRequestFactory as parameter to its constructor:

    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
    interceptors.add( new NetworkInterceptor() );

    SimpleClientHttpRequestFactory s = new SimpleClientHttpRequestFactory();
    s.setReadTimeout(5000);
    s.setConnectTimeout(1000);

    RestTemplate tpl = new RestTemplate(s);//Or however you instantiated it
    tpl.setInterceptors( interceptors );

    ClientHttpRequestFactory c =  tpl.getRequestFactory();

Hope it helps.

like image 98
eltabo Avatar answered Nov 05 '22 03:11

eltabo


i see the androidannotations document has @Rest annotations

@Rest(rootUrl="yourRootUrl",requestFactory=AppRequestFacetory.class,converters ={..},interceptors={..})
public interface RestApis extends RestClientErrorHandling{...};

AppRequestFacetory.class set TIMEOUT as belows:

@EBean
class AppRequestFactory extends SimpleClientHttpRequestFactory {

     @AfterInject
     void afterinject() {
         setReadTimeout(20*1000); //set 20s read timeout
         setConnectTimeout(20*1000); //set 20s connect timeout
     }
}

and it works . enjoy androidannotations rest api

like image 7
mrljdx Avatar answered Nov 05 '22 03:11

mrljdx