我在我的项目中实现了robospice,并对所有api调用使用了改进。对于一些请求,我需要增加超时时间,请让我知道我该怎么做?
实际上,我使用的服务扩展了reformationsonspiceservice。
我的服务类代码如下:
public class MyService extends RetrofitGsonSpiceService {
@Override
public void onCreate() {
super.onCreate();
addRetrofitInterface(MyInterface.class);
}
@Override
public CacheManager createCacheManager(Application application) throws CacheCreationException {
CacheManager cacheManager = new CacheManager();
ObjectPersisterFactory persistFactory = new RetrofitObjectPersisterFactory(application,
getConverter(), getCacheFolder());
persistFactory.setAsyncSaveEnabled(true);
cacheManager.addPersister(persistFactory);
return cacheManager;
}
@Override
protected String getServerUrl() {
return Utils.getBaseUrl();
}
@Override
protected RestAdapter.Builder createRestAdapterBuilder() {
RestAdapter.Builder builder = new RestAdapter.Builder().setRequestInterceptor(
new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader(Const.HEADER_DEVICE_TYPE_KEY,
Const.HEADER_DEVICE_TYPE_VALUE);
}
}
);
builder.setEndpoint(getServerUrl()).setConverter(getConverter());
return builder;
}
}
最佳答案
我在这里遇到了一个类似的问题,最终在别处找到了答案。如果这里有一个更完整的例子,我会节省一些时间,所以我回过头来贴出对我有用的东西,以防万一:
读取超时增加的适配器
// create client
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(60 * 1000, TimeUnit.MILLISECONDS);
// create rest adapter using the client above
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(getBaseApiUrl())
.setClient(new OkClient(okHttpClient))
// this gson converter below is optional. We use it for parsing dates and enums
.setConverter(new GsonConverter(createApiGson()))
.setLogLevel(getRetrofitLogLevel())
.build();
注意:对于我们,
getBaseApiUrl()
返回如下内容:https://some.company.com/api/
getRetrofitLogLevel()
返回RestAdapter.LogLevel.FULL
或RestAdapter.LogLevel.NONE
取决于构建的应用程序的风格。最后,这些是使一切正常工作的主要依赖关系:
关键依赖项
dependencies {
...
compile "com.squareup.retrofit:retrofit:1.5.0"
compile "com.squareup.retrofit:retrofit-mock:1.5.0"
compile "com.squareup.okhttp:okhttp:1.5.4"
compile "com.google.code.gson:gson:2.2.4"
...
}