Android开发Android技术知识Android开发经验谈

Android:OkHttp/Retrofit2配置(日志/拦截

2019-04-24  本文已影响55人  Alisallon

配置日志

    // Gradle中需要添加依赖:
    // implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
    if (BuildConfig.DEBUG) {
        // 声明日志类
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        // 设定日志级别
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
    }

配置拦截器

val okHttpClient = OkHttpClient.Builder()
okHttpClient.addInterceptor {
    // 获得请求信息
    val requestBuilder = it.request().newBuilder()
    MainApplication.getContext()?.let { context ->
        val timestamp = System.currentTimeMillis()
        // 添加headers信息
        requestBuilder
                .addHeader("packageName", MainApplication.getPackageName()) // 应用包名
                .addHeader("timestamp", timestamp.toString()) // 请求时间戳
    }
    val request = requestBuilder.build()
    if (BuildConfig.DEBUG) {
        // 记录请求耗时
        val startNs = System.nanoTime()
        val response: okhttp3.Response
        try {
            // 发送请求
            response = it.proceed(request)
        } catch (e: Exception) {
            Logger.logE(javaClass.name, e)
            throw e
        }
        val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)
        // 获得返回的body
        val responseBody = response.body()
        // 获得buffer对象
        val source = responseBody!!.source()
        source.request(java.lang.Long.MAX_VALUE) // Buffer the entire body.
        // 获得返回的数据
        val buffer = source.buffer()
        val contentType = response.header("content-type")
        var responseData: String? = null
        if (contentType != null) {
            if (contentType.contains("image")) {
                responseData = "this is a image"
            } else if (contentType.contains("application/json")) {
                // clone()后使用buffer
                responseData = buffer.clone().readString(Charset.forName("UTF-8"))
            }
        }
        // 打印请求耗时
        Logger.logD(javaClass.name, "\r\n"
                + "url:" + request.url() + "\r\n"
                + "method:" + request.method() + "\r\n"
                + "request header:" + "\r\n"
                + "==============\r\n"
                + request.headers().toString()
                + "==============\r\n"
                + "request body:" + request.body().toString() + "\r\n"
                + "elapsed time:" + tookMs + "ms" + "\r\n"
                + "response header:" + "\r\n"
                + "==============\r\n"
                + response.headers().toString()
                + "==============\r\n"
                + "response:" + responseData + "\r\n")
        response
    } else {
        it.proceed(request)
    }
}

配置https证书

    fun init() {
        val okHttpClient = OkHttpClient.Builder()
        try {
            // 配置https证书
            // 证书位置:/src/main/assets/xxxx.cer
            setCertificates(okHttpClient, MainApplication.getContext()!!.assets.open("server.cer"))
            okHttpClient.hostnameVerifier { _, _ -> true }
        } catch (e: IOException) {
            Logger.logE(javaClass.name, e)
        }
    }

    /**
     * 配置https证书
     * @param clientBuilder OKhttpClient.builder
     * @param certificates 读取证书的InputStream
     */
    private fun setCertificates(clientBuilder: OkHttpClient.Builder, certificateIs: InputStream) {
        try {
            val certificateFactory = CertificateFactory.getInstance("X.509")
            val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
            val certificate = certificateFactory.generateCertificate(certificateIs)
            Logger.logD(javaClass.name, "subjectDN: " + (certificate as X509Certificate).subjectDN)
            Logger.logD(javaClass.name, "publicKey: " + certificate.publicKey)
            keyStore.load(null, null)
            keyStore.setCertificateEntry("selfCA", certificate)
            certificateIs.close()
            val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
            trustManagerFactory.init(keyStore)
            val trustManagers = trustManagerFactory.trustManagers
            if (trustManagers.size != 1 || trustManagers[0] !is X509TrustManager) {
                throw IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers))
            }
            val trustManager = trustManagers[0] as X509TrustManager
            val sslContext = SSLContext.getInstance("TLS")
            // Create an SSLContext that uses our TrustManager
            sslContext.init(null, trustManagerFactory.trustManagers, SecureRandom())
            val sslSocketFactory = sslContext.socketFactory
            clientBuilder.sslSocketFactory(sslSocketFactory, trustManager)
        } catch (e: Throwable) {
            Logger.logE(javaClass.name, e)
        }
    }
上一篇下一篇

猜你喜欢

热点阅读