I use Android's recommended Cronet library for making HTTP requests, however, I couldn't find information on how to implement certain features. For example, I need to set max wait time for all HTTP requests. In other words, if the HTTP request takes more than 'X' seconds - it should be considered as a FAILED request. How can I configure this in Cronet?
My code:
fun initCronet() { // this is called only once
executor = Executors.newSingleThreadExecutor()
engine = CronetEngine.Builder(context)
.enableHttp2(true)
.build()
}
suspend fun myFunction() {
suspendCoroutine<HttpResponseContainer> {
val callback = CoroutinesNetworkCallback(it)
val url = "http://myhost.com/my-endpoint"
engine.newUrlRequestBuilder(url, callback, executor)
.addHeader("Content-Type", "application/json; charset=UTF-8")
.build().start()
}
}
Callback looks approximately like this:
class CoroutinesNetworkCallback (
private val continuation: Continuation<HttpResponseContainer>,
) : UrlRequest.Callback() {
override fun onRedirectReceived(request: UrlRequest, info: UrlResponseInfo, newUrl: String) {
request.cancel()
}
override fun onResponseStarted(request: UrlRequest, info: UrlResponseInfo) {
// init buffer
}
override fun onReadCompleted(request: UrlRequest, info: UrlResponseInfo, buffer: ByteBuffer) {
// retrieve response
}
override fun onFailed(request: UrlRequest, info: UrlResponseInfo, error: CronetException) {
continuation.resumeWithException(RuntimeException("request failed"))
}
override fun onSucceeded(request: UrlRequest, info: UrlResponseInfo) {
continuation.resume(HttpResponseContainer(httpStatusCode))
}
}
you can add connectTimeout , writeTimeout and readTimeout with builder
connectTimeout : max time to try connect with host address writeTimeout and readTimeout : max time to send request and receive response