public class ServicioConexionRetrofitXML {
public static final String API_BASE_URL = new GestorPreferencias().getPreferencias().getHost();
public static final long tiempoMaximoRespuestaSegundos = 60;
public static final long tiempoMaximoLecturaSegundos = 100;
public static final OkHttpClient clienteOkHttp = new OkHttpClient();
private static RestAdapter.Builder builder = new RestAdapter.Builder().
setEndpoint(API_BASE_URL).
setClient(new OkClient(clienteOkHttp)).setConverter(new SimpleXMLConverter());
public static <S> S createService(Class<S> serviceClass) {
clienteOkHttp.setConnectTimeout(tiempoMaximoRespuestaSegundos, TimeUnit.SECONDS);
clienteOkHttp.setReadTimeout(tiempoMaximoLecturaSegundos, TimeUnit.SECONDS);
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
}
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.6.0'
// Librería de retrofit para XML converter (Simple) Se excluyen grupos para que no entre
// en conflicto.
compile('com.squareup.retrofit:converter-simplexml:1.9.0') {
exclude group: 'xpp3', module: 'xpp3'
exclude group: 'stax', module: 'stax-api'
exclude group: 'stax', module: 'stax'
}
9 回答
您可以在底层HTTP客户端上设置超时 . 如果您未指定客户端,则Retrofit将创建一个具有默认连接和读取超时的客户端 . 要设置自己的超时,您需要配置自己的客户端并将其提供给
RestAdapter.Builder
.一个选项是使用OkHttp客户端,也来自Square .
1. Add the library dependency
在build.gradle中,包含以下行:
x.x.x
是所需的库版本 .2. Set the client
例如,如果要将超时设置为60秒,请对版本2之前的Retrofit和版本3之前的Okhttp( FOR THE NEWER VERSIONS, SEE THE EDITS )执行此操作:
EDIT 1
对于自
3.x.x
以来的okhttp版本,您必须以这种方式设置依赖关系:并使用构建器模式设置客户端:
更多信息Timeouts
EDIT 2
自
2.x.x
以来的改造版本也使用构建器模式,因此将上面的返回块更改为:如果使用类似我的
providesRestAdapter
方法的代码,则将方法返回类型更改为Retrofit .更多信息在Retrofit 2 — Upgrade Guide from 1.9
ps:如果你的minSdkVersion大于8,你可以使用
TimeUnit.MINUTES
:有关单位的更多详细信息,请参阅TimeUnit .
这些答案对我来说已经过时了,所以这就是它如何解决的问题 .
添加OkHttp,在我的情况下版本是
3.3.1
:然后在构建您的Retrofit之前,执行以下操作:
我正在使用 Retrofit 1.9 获取 XML .
如果您使用的是Retrofit 1.9.0和okhttp 2.6.0,请添加到您的Gradle文件中 .
注意:如果您需要获取 JSON ,只需从上面的代码中删除即可 .
对于使用OkHttp3用户的Retrofit1.9,这是解决方案,
这将是设置每个服务超时的最佳方法(将超时作为参数传递)
不要错过OkHttpClient .
希望这对任何人都有帮助 .
我找到了这个例子
https://github.com/square/retrofit/issues/1557
这里我们在构建API rest服务实现之前设置自定义url客户端连接客户端 .