如何在RestTemplate中添加超时

时间:2016-06-01 12:00:20

标签: android resttemplate connection-timeout android-annotations

我需要在我的代码中添加超时这是我的代码,但我不知道如何修改此代码以添加超时。

`

 @EBean(scope = EBean.Scope.Singleton)
public class KioraRestClient {

public static final String SERVER_HOST         = KioraBuildConfig.REST_SERVER_API_URL;
public static final String VERSION_SERVER_HOST = KioraBuildConfig.REST_VERSION_SERVER_API_URL;


@AfterInject
void Initialize() {

    try {
        turnOffSslChecking();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    // this factory needs to be crated here since requires some injected dependencies
    ClientHttpRequestFactory keyPairRequestFactory = new KioraHttpRequestFactory(
            new ContentAuthUriDecorator(authPreferences)
    );

    ClientHttpRequestFactory timeoutFactory = new SimpleTimeoutRequestFactory();        


    //TODO: Extract common interface for the controllers
    LicenseController.getRestTemplate().setRequestFactory(keyPairRequestFactory);
    UserController.getRestTemplate().setRequestFactory(keyPairRequestFactory);
    ContentController.getRestTemplate().setRequestFactory(keyPairRequestFactory);

    VersionController.getRestTemplate().setRequestFactory(timeoutFactory);
    RootIPController.getRestTemplate().setRequestFactory(keyPairRequestFactory);

    PurchaseController.getRestTemplate().setRequestFactory(keyPairRequestFactory);
    HotspotController.getRestTemplate().setRequestFactory(keyPairRequestFactory);

`

我尝试添加这样的超时但这个20秒的超时似乎没有效果`

HttpComponentsClientHttpRequestFactory  httpRequestFactory =  new     HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectTimeout(20 * 1000); 
 PurchaseController.getRestTemplate().setRequestFactory(httpRequestFactory);
    HotspotController.getRestTemplate().setRequestFactory(httpRequestFactory);

`

1 个答案:

答案 0 :(得分:0)

您只设置连接超时未读取超时。连接超时定义了在放弃尝试连接之前等待的时间。但是,读取超时定义了等待响应的时间。

以相同的方式设置读取超时,您将能够看到它生效

httpRequestFactory.setReadTimeout(20 * 1000);

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/client/HttpComponentsClientHttpRequestFactory.html#setReadTimeout-int-