如何使用 OkHttp3 获取 Http 错误代码

问题描述 投票:0回答:1

我在我的 Android 应用程序中使用 OkHttp3。 我的问题是唯一正确返回的响应是 200。所有其他响应都会引发异常。 有什么方法可以防止它引发异常并获取响应代码。

这是我的代码:

        try {
        val network: Network? = connectivityManager.activeNetwork
        val capabilities = connectivityManager.getNetworkCapabilities(network)
        val httpBuilder = OkHttpClient.Builder()
            .connectTimeout(100000, TimeUnit.MILLISECONDS)
            .readTimeout(100000, TimeUnit.MILLISECONDS)
            .socketFactory(network!!.socketFactory)
        val okHttpClient = httpBuilder.build()

        val request = Request.Builder().url(urlString).build()

        okHttpClient.newCall(request).execute().use {response ->
            Log.d(TAG, "Network response: ${response.networkResponse}")
            httpRequestResult.onSuccess(response.networkResponse.toString())

    } catch (e: SocketTimeoutException) {
        Log.d(TAG, "SocketTimeoutException: ${e}")
    }catch (e: Exception) {
        Log.d(TAG, "Exception: ${e}")
    }

我使用socketFactory,因为我想确保它使用wifi连接,即使移动数据也打开了。

这可以做到还是我的方法完全错误。

android okhttp
1个回答
0
投票
  1. 捕获更通用的 IOException,而不是特定的 SocketTimeoutException。这将涵盖其他 IO 相关的异常。

  2. 使用response.code()来检索HTTP状态代码。

try {
    val network: Network? = connectivityManager.activeNetwork
    val capabilities = connectivityManager.getNetworkCapabilities(network)
    val httpBuilder = OkHttpClient.Builder()
        .connectTimeout(100000, TimeUnit.MILLISECONDS)
        .readTimeout(100000, TimeUnit.MILLISECONDS)
        .socketFactory(network!!.socketFactory)
    val okHttpClient = httpBuilder.build()

    val request = Request.Builder().url(urlString).build()

    okHttpClient.newCall(request).execute().use { response ->
        val statusCode = response.code()
        Log.d(TAG, "HTTP Status Code: $statusCode")

        // Handle response based on status code
        if (response.isSuccessful) {
            // Process successful response
            val responseBody = response.body()?.string()
            Log.d(TAG, "Response Body: $responseBody")
            httpRequestResult.onSuccess(responseBody)
        } else {
            // Process unsuccessful response
            val errorBody = response.body()?.string()
            Log.d(TAG, "Error Body: $errorBody")
            httpRequestResult.onFailure("HTTP Status Code: $statusCode, Error Body: $errorBody")
        }
    }
} catch (e: IOException) {
    Log.d(TAG, "IOException: $e")
}
© www.soinside.com 2019 - 2024. All rights reserved.