Response Validation

预计阅读时间:1分钟

此功能允许验证HTTP响应并处理引擎和管道中的转换异常.

此功能在io.ktor.client.features.HttpCallValidator类中定义,并且不需要其他构件.

Configuration

要配置响应验证功能,请使用validateResponsehandleResponseException方法:

HttpResponseValidator {
    validateResponse { response: HttpResponse ->
        // ...
    }

    handleResponseException { cause: Throwable ->
        // ...
    }
}

可以多次配置此功能. 所有验证器和处理程序都将按安装顺序保存并调用.

Expect success

使用响应验证实现的ExpectSuccess功能:

HttpResponseValidator {
    validateResponse { response ->
        val statusCode = response.status.value
        when (statusCode) {
            in 300..399 -> throw RedirectResponseException(response)
            in 400..499 -> throw ClientRequestException(response)
            in 500..599 -> throw ServerResponseException(response)
        }

        if (statusCode >= 600) {
            throw ResponseException(response)
        }
    }
}

该功能默认情况下已安装,但可以在客户端配置中禁用:

val client = HttpClient() {
    expectSuccess = false
}

by  ICOPY.SITE