OkHttpClient.Builder client = new OkHttpClient.Builder();
client.connectTimeout(REQUEST_TIME, TimeUnit.SECONDS)
.readTimeout(REQUEST_TIME, TimeUnit.SECONDS)
.writeTimeout(REQUEST_TIME, TimeUnit.SECONDS);
mRetrofit = new Retrofit.Builder()
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(NetUrl.BASE_URL)
.build();
I want to modify the timeout time of a request, and other requests dont modify.How to do ?
The only way to do this is by putting a header on your interface method which you then read in an interceptor and call its methods to adjust the timeout.
We should probably add this as a sample...
@JakeWharton thanks
class TimeHeaderInterceptor : Interceptor {
companion object {
private const val CONNECT_TIMEOUT = "CONNECT_TIMEOUT"
private const val READ_TIMEOUT = "READ_TIMEOUT"
private const val WRITE_TIMEOUT = "WRITE_TIMEOUT"
}
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
var connectTimeout = chain.connectTimeoutMillis()
var readTimeout = chain.readTimeoutMillis()
var writeTimeout = chain.writeTimeoutMillis()
val builder = request.newBuilder()
request.header(CONNECT_TIMEOUT)?.also {
connectTimeout = it.toInt()
builder.removeHeader(CONNECT_TIMEOUT)
}
request.header(READ_TIMEOUT)?.also {
readTimeout = it.toInt()
builder.removeHeader(READ_TIMEOUT)
}
request.header(WRITE_TIMEOUT)?.also {
writeTimeout = it.toInt()
builder.removeHeader(WRITE_TIMEOUT)
}
return chain.run {
withConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
withReadTimeout(readTimeout, TimeUnit.MILLISECONDS)
withWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS)
proceed(builder.build())
}
}
}
OkHttpClient.Builder()
.connectTimeout(15_000, TimeUnit.MILLISECONDS)
.writeTimeout(15_000, TimeUnit.MILLISECONDS)
.readTimeout(15_000, TimeUnit.MILLISECONDS)
.addInterceptor(TimeHeaderInterceptor()) // config
.build()
interface HttpApiImpl {
/**
* 动态配置时间,例子
*
*/
@Headers("CONNECT_TIMEOUT:1000", "READ_TIMEOUT:5000", "WRITE_TIMEOUT:2000")
@GET
fun time(@Url url: String): Observable<String>
}
Most helpful comment
The only way to do this is by putting a header on your interface method which you then read in an interceptor and call its methods to adjust the timeout.
We should probably add this as a sample...