Kotlin OKHTTP3和拦截器的使用

news/2025/3/31 22:22:47/

注意:在android6.0以后网络请求还需如下配置:

 android:usesCleartextTraffic="true"

<applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:usesCleartextTraffic="true"android:theme="@style/AppTheme">***
</application>

一、引入okhttp3包

 //okhttp3implementation("com.squareup.okhttp3:okhttp:4.9.0")implementation("com.squareup.okhttp3:logging-interceptor:4.9.0")

二、创建单例对象

package com.example.buju.httpimport android.content.Context
import android.os.Environment
import android.util.Log
import android.widget.Toast
import okhttp3.Call
import okhttp3.Callback
import okhttp3.FormBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit
/*** 单例对象*  -http请求工具类* */
object HiOkhttp {/*  private val client:OkHttpClient// 最早调用模块init {val httpLoggingInterceptor = HttpLoggingInterceptor()// okhttp3自带拦截器httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)client = OkHttpClient.Builder()// builder构造者设计模式.connectTimeout(10,TimeUnit.SECONDS)//连接超时时间.readTimeout(10,TimeUnit.SECONDS)// 读取超时.writeTimeout(10,TimeUnit.SECONDS)// 写超时.addInterceptor(httpLoggingInterceptor)// 自带拦截器.build()}*/val client = OkHttpClient.Builder()// builder构造者设计模式.connectTimeout(10,TimeUnit.SECONDS)//连接超时时间.readTimeout(10,TimeUnit.SECONDS)// 读取超时.writeTimeout(10,TimeUnit.SECONDS)// 写超时.addInterceptor(LoggingInterceptor())// 自定义拦截器.build()// android 分为主线程和子线程// 主线程就是APP一启动后,咱们android framework层会启动一个线程,主线程(UI线程)// 子线程 - new Thread().start()/*** get请求*  -同步请求不要放在主线程中执行,容易阻塞线程* */fun syncGet(url:String){// 构造请求体val request:Request = Request.Builder().url(url).build()// 构造请求对象val call:Call = client.newCall(request)Thread(Runnable {// 构建子线程// execute() - 发起同步请求(同步执行)val  response:Response = call.execute()val body: String? = response.body?.string()Log.e("OKHTTP","get response:${body}")}).start()}/*** get请求*  -异步请求* */fun asyncGet(url:String){// 构造请求体val request:Request = Request.Builder().url(url).build()// 构造请求对象val call:Call = client.newCall(request)// enqueue() - 发起异步请求(异步执行)call.enqueue(object :Callback{override fun onFailure(call: Call, e: IOException) {Log.e("OKHTTP","get onFailure:${e.message}")}override fun onResponse(call: Call, response: Response) {val body:String? = response.body?.string()Log.e("OKHTTP","get response:${body}")}})}/*** post请求*  -同步表单请求,不要放在主线程中执行,容易阻塞线程* */fun syncPost(url:String){val body = FormBody.Builder().add("userId","123").add("userName","zs").build()val request:Request = Request.Builder().url(url).post(body).build()val call:Call = client.newCall(request)Thread(Runnable {val response:Response = call.execute()val resultBody = response.body?.string()Log.e("OKHTTP","post response:${resultBody}")}).start()}/*** post请求*  -异步表单请求* */fun asyncPost(url:String){val body = FormBody.Builder().add("userId","123").add("userName","zs").build()val request:Request = Request.Builder().url(url).post(body).build()val call:Call = client.newCall(request)call.enqueue(object :Callback{override fun onFailure(call: Call, e: IOException) {Log.e("OKHTTP","post onFailure:${e.message}")}override fun onResponse(call: Call, response: Response) {val resultBody = response.body?.string()Log.e("OKHTTP","post response:${resultBody}")}})}/*** post请求*  -异步多表单文件上传请求*  -url必须支持文件上传的接口*  -android6.0以后,读取外部存储卡的文件都是需要动态申请权限* */fun asyncPostMultipart(url:String,context:Context){val file = File(Environment.getExternalStorageDirectory(),"demo.png")if (!file.exists()){Toast.makeText(context,"文件不存在",Toast.LENGTH_LONG).show()return}val body = MultipartBody.Builder().addFormDataPart("key1","value1").addFormDataPart("key2","value2").addFormDataPart("file","file.png",RequestBody.create("application/octet-stream".toMediaType(), file)).build()val request:Request = Request.Builder().url(url).post(body).build()val call:Call = client.newCall(request)call.enqueue(object :Callback{override fun onFailure(call: Call, e: IOException) {Log.e("OKHTTP","post onFailure:${e.message}")}override fun onResponse(call: Call, response: Response) {val resultBody = response.body?.string()Log.e("OKHTTP","post response:${resultBody}")}})}/*** post请求*  -异步字符串请求* */fun asyncPostString(url:String){// 纯文本/* val textPlain = "text/plain;charset=utf-8".toMediaType()val textObj = "username:username;password:1234"val body = RequestBody.create(textPlain,textObj)*/// json对象val applicationJson = "application/json;charset=utf-8".toMediaType();val jsonObj = JSONObject()jsonObj.put("key1","val1")jsonObj.put("key2","val2")val body = RequestBody.create(applicationJson,jsonObj.toString())val request = Request.Builder().url(url).post(body).build()val call:Call = client.newCall(request)call.enqueue(object :Callback{override fun onFailure(call: Call, e: IOException) {Log.e("OKHTTP","post onFailure:${e.message}")}override fun onResponse(call: Call, response: Response) {val resultBody = response.body?.string()Log.e("OKHTTP","post response:${resultBody}")}})}}

三、自定义okhttp3拦截器

package com.example.buju.httpimport android.util.Log
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer/*** OKHttp3 拦截器* */
class LoggingInterceptor:Interceptor {override fun intercept(chain: Interceptor.Chain): Response {val time_start = System.nanoTime()// 开始时间戳val request = chain.request()// 请求val response = chain.proceed(request)// 响应/*** 获取请求信息* */val buffer = Buffer()// okio.Bufferrequest.body?.writeTo(buffer)val requestBodyStr = buffer.readUtf8()// request.url - 请求接口;requestBodyStr - 请求携带的参数Log.e("OKHTTP",String.format("Sending request %s with params %s",request.url,requestBodyStr))/*** 获取响应信息* */val bussinessData:String = response.body?.string()?:"response body null"val mediaType = response.body?.contentType()val newBody = ResponseBody.create(mediaType,bussinessData)val newResponse = response.newBuilder().body(newBody).build()val time_end = System.nanoTime()//结束始时间戳//  request.url - 请求接口;(time_end - time_start) -执行时间;bussinessData - 响应数据Log.e("OKHTTP",String.format("Received response for %s in %.1fms >>> %s",request.url,(time_end - time_start),bussinessData))return newResponse}}


http://www.ppmy.cn/news/1383616.html

相关文章

二刷代码随想录算法训练营第二十三天 | 669. 修剪二叉搜索树、108.将有序数组转换为二叉搜索树、538.把二叉搜索树转换为累加树

目录 一、669. 修剪二叉搜索树 二、108. 将有序数组转换为二叉搜索树 三、538. 把二叉搜索树转换为累加树 一、669. 修剪二叉搜索树 题目链接&#xff1a;力扣 文章讲解&#xff1a;代码随想录 视频讲解&#xff1a; 你修剪的方式不对&#xff0c;我来给你纠正一下&#…

Cron 表达式

Cron 表达式包括以下 7 个字段&#xff1a; 格式: [秒] [分] [小时] [日] [月] [周] [年] 序号 说明 是否必填 允许填写的值 允许的通配符 1 秒 是 0-59 , - * / 2 分 是 0-59 , - * / 3 小时 是 0-23 , - * / 4 日 是 1-31 , - * ? / L W 5 月 是 1-12 or JAN-DEC , - * / 6…

【Docker】Memcached 容器化部署

Memcached环境标准软件基于Bitnami Memcached 构建。当前版本为1.6.24 你可以通过轻云UC部署工具直接安装部署&#xff0c;也可以手动按如下文档操作&#xff0c;该项目已经全面开源&#xff0c;可以从如下环境获取 配置文件地址: https://gitee.com/qingplus/qingcloud-platf…

简介:CMMI软件能力成熟度集成模型

前言 CMMI是英文Capability Maturity Model Integration的缩写。 CMMI认证简称软件能力成熟度集成模型&#xff0c;是鉴定企业在开发流程化和质量管理上的国际通行标准&#xff0c;全球软件生产标准大都以此为基点&#xff0c;并都努力争取成为CMMI认证队伍中的一分子。 对一个…

棉纺行业的股票怎么样?洪书敏老师经验值得深思,推荐保持学习

受美棉强势上涨影响,国内棉纺行业迎来“开门红”。财联社记者从业内采访获悉,海外市场需求复苏回暖,已有大型纺企陆续提价,国内方面,棉花库存逐步下降,棉花加工企业、纺企盈利有所改善,开工率明显提升,棉纺行业“金三银四”将至,但受此前下游需求疲弱影响,市场观望情绪仍然较浓…

Nginx的日志怎么看,在哪看,access.log日志内容详解

Nginx 的日志文件通常位于服务器的文件系统中&#xff0c;具体位置可能因配置而异。以下是查看 Nginx 日志的几种方法&#xff1a; 1、查看访问日志&#xff1a;在默认配置下&#xff0c;Nginx 的访问日志文件路径为 /var/log/nginx/access.log。您可以通过命令 sudo cat /var…

【开源-土拨鼠充电系统】鸿蒙 HarmonyOS 4.0+微信小程序+云平台

本人自己开发的开源项目&#xff1a;土拨鼠充电系统 ✍GitHub开源项目地址&#x1f449;&#xff1a;https://github.com/cheinlu/groundhog-charging-system ✍Gitee开源项目地址&#x1f449;&#xff1a;https://gitee.com/cheinlu/groundhog-charging-system ✨踩坑不易&am…

7. C++编辑器合成默认构造函数的问题

1. C编辑器合成默认构造函数的问题 问题&#xff1a;C面向对象编程时&#xff0c;如果我们没有声明任何构造函数constructor&#xff0c;按照以前最初学习&#xff0c;说编译器会自动合成一个默认的无参构造函数default constructor&#xff0c;但是事实确实是这样吗&#xff…