使用AndroidAnnotations处理超时(Spring Rest)

时间:2014-01-30 08:35:33

标签: android spring rest spring-mvc android-annotations

基本上,我今天面临的是:

  • 处理休息时请求超时。

似乎是简单的编写,但不是很容易编码。

这是我到目前为止的实施:

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

tpl.setInterceptors( interceptors );

现在,在设置拦截器之后,我想为模板设置自定义超时配置。

所以我做了以下事情: tpl.getRequestFactory()

如果没有设置拦截器,则返回InterceptingClientHttpRequestFactory而不是SimpleClientHttpRequestFactory

因此,当它返回InterceptingClientHttpRequestFactory实例时,我无法设置超时。

您可以查看Spring的源代码,最后一种方法: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

所以......有什么提示吗?

3 个答案:

答案 0 :(得分:7)

假设 tpl 是一个RestTemplate,您可以将SimpleClientHttpRequestFactory作为参数传递给它的构造函数:

    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();

希望它有所帮助。

答案 1 :(得分:6)

我看到androidannotations文档有@Rest注释

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

AppRequestFacetory.class将TIMEOUT设置为:

@EBean
class AppRequestFactory extends SimpleClientHttpRequestFactory {

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

它有效。享受androidannotations rest api

答案 2 :(得分:0)

当我需要配置Android注释时,我会使用以下代码:

    ClientHttpRequestFactory requestFactory = restClient.getRestTemplate().getRequestFactory();
    if (requestFactory instanceof SimpleClientHttpRequestFactory) {
        Log.d("HTTP", "HttpUrlConnection is used");
        ((SimpleClientHttpRequestFactory) requestFactory).setConnectTimeout(3 * 1000);
        ((SimpleClientHttpRequestFactory) requestFactory).setReadTimeout(3 * 1000);
    } else if (requestFactory instanceof HttpComponentsClientHttpRequestFactory) {
        Log.d("HTTP", "HttpClient is used");
        ((HttpComponentsClientHttpRequestFactory) requestFactory).setReadTimeout(3 * 1000);
        ((HttpComponentsClientHttpRequestFactory) requestFactory).setConnectTimeout(3 * 1000);
    }