Okhttp-LoggingInterceptor的简单使用

文章介绍了如何使用Okhttp框架中的拦截器功能,特别是HttpLoggingInterceptor,用于监控和控制网络请求的日志。通过自定义LoggingInterceptor,可以精确地打印请求URL、请求体和响应时间,从而避免冗余日志,提高日志的可读性和实用性。
摘要由CSDN通过智能技术生成
概述

Okhttp除了提供强大的get,post网络请求外,还包含请求日志的拦截器,可以监视,重写,重试调用请求。

简单使用

我们在构造OkHttpClient时,通过addInterceptor()方法添加我们需要的过滤器。

   object OkhttpUtils{
    ……
    private var client:OkHttpClient

    //init方法在kotlin静态类中,是最先被调用的方法
    init {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        //构造Http对象
        client = OkHttpClient().newBuilder()
            .connectTimeout(10L, TimeUnit.SECONDS)
            .readTimeout(10L, TimeUnit.SECONDS)
            .writeTimeout(10L, TimeUnit.SECONDS)
            .addInterceptor(httpLoggingInterceptor)
            .build()
    }
    
    ……
   }
httpLoggingInterceptor

使用默认的httpLoggingInterceptor打印日志如下,可以发现,除了关键信息外,还有一些冗余或者很长的非关键日志,我们可以通过自定义日志过滤器找到我们需要的信息。

 自定义LoggingInterceptor

1:写一个类,实现Interceptor接口,复写intercept(chain:Interceptor.Chain):Response{}方法

package com.example.okhttp.http

import android.util.Log
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.Buffer

class TypeInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val time = System.currentTimeMillis()
        //获取request
        val request = chain.request()
        //request.body转字符串
        val str = request.body?.toString() ?: "request.body is null"
        Log.d(
            Hiokhttp.TAG, String.format(
                "sending request url is %s with body is %s",
                request.url, str
            )
        )
        //获取response,因为okhttp的原理,response.body在获取一次以后,
        //就不能再生成响应流了,因此需要构造一个新的返回
        val response = chain.proceed(request = request)
        //将response的数据保存到新的response
        val data: String = response.body?.string() ?: "response.body is null"

        //构建新的response
        val medieType = request.body?.contentType()
        val newBody = data.toResponseBody(medieType)
        val end = System.currentTimeMillis()
        Log.d(
            Hiokhttp.TAG, String.format(
                "received url is %s with host time %.1f ms ",
                request.url, (end - time) / 1e3
            )
        )
        return response.newBuilder().body(newBody).build()

    }
}

下面看一下效果,我们将请求url和请求体,以及花费时间 成功打印了出来,避免冗余繁琐的日志。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是 okhttp-eventsource 的使用示例: 1. 添加依赖 在项目的 build.gradle 文件中添加以下依赖: ```groovy implementation 'com.squareup.okhttp3:okhttp:版本号' implementation 'com.github.morihacky:okhttp-eventsource:版本号' ``` 2. 创建 EventSource ```java OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://example.com/events") .build(); EventSource eventSource = new EventSource.Builder(callback, request) .build(); ``` 3. 实现回调 ```java EventSource.Listener callback = new EventSource.Listener() { @Override public void onOpen(EventSource eventSource, Response response) { // 连接成功 } @Override public void onMessage(EventSource eventSource, String id, String type, String data) { // 处理消息 } @Override public void onComment(EventSource eventSource, String comment) { // 处理注释 } @Override public boolean onRetryTime(EventSource eventSource, long milliseconds) { // 确定是否重新连接 return true; } @Override public boolean onRetryError(EventSource eventSource, Throwable throwable, Response response) { // 确定是否重新连接 return true; } @Override public void onClosed(EventSource eventSource) { // 连接关闭 } @Override public void onFailure(EventSource eventSource, Throwable t, Response response) { // 连接失败 } }; ``` 4. 连接和关闭 ```java // 连接 eventSource.start(); // 关闭 eventSource.close(); ``` 以上就是 okhttp-eventsource 的使用示例。通过这个库,你可以轻松地实现 SSE(Server-Sent Events)协议,从服务器实时接收信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunbofiy23

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值