4

我在我的 Android 应用程序中使用以下代码来使用 RestTemplates

return getRestTemplate().postForObject(url, forgotPasswordRequest,
                ForgetPassword.Response.class);

现在我如何设置请求的超时时间并使用超时侦听器来捕获请求超时?

亲切的问候

4

1 回答 1

3
RestTemplate restTemplate = new MyRestTemplate(10*1000);
return restTemplate.postForObject(url, forgotPasswordRequest,
            ForgetPassword.Response.class);

[...]


protected class MyRestTemplate extends RestTemplate {
    public MyRestTemplate(int timeout) {
        if (getRequestFactory() instanceof SimpleClientHttpRequestFactory) {
            Log.d("HTTP", "HttpUrlConnection is used");
            ((SimpleClientHttpRequestFactory) getRequestFactory()).setConnectTimeout(timeout);
            ((SimpleClientHttpRequestFactory) getRequestFactory()).setReadTimeout(timeout);
        } else if (getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) {
            Log.d("HTTP", "HttpClient is used");
            ((HttpComponentsClientHttpRequestFactory) getRequestFactory()).setReadTimeout(timeout);
            ((HttpComponentsClientHttpRequestFactory) getRequestFactory()).setConnectTimeout(timeout);
        }
    }
}
于 2013-06-20T11:36:58.793 回答