Kotlin OKHTTP3和拦截器的使用

注意:在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.mzph.cn/news/740893.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

掘根宝典之C++迭代器简介

在C中&#xff0c;容器是一种用于存储和管理数据的数据结构。C标准库提供了多种容器&#xff0c;每种容器都有其独特的特点和适用场景。 我们知道啊&#xff0c;我们可以通过下标运算符来对容器内的元素进行访问&#xff0c;但是只有少数几种容器才同时支持下标运算符&#xf…

闲聊电脑(7)常见故障排查

闲聊电脑&#xff08;7&#xff09;常见故障排查 夜深人静&#xff0c;万籁俱寂&#xff0c;老郭趴在电脑桌上打盹&#xff0c;桌子上的小黄鸭和桌子旁的冰箱又开始窃窃私语…… 小黄鸭&#xff1a;冰箱大哥&#xff0c;平时遇到电脑故障该咋处理呢&#xff1f; 冰箱&#xf…

k8s中calico网络组件部署时一个节点一直处于Pending状态

k8s中calico网络组件部署时一个节点一直处于Pending状态 故障截图 故障排查思路&#xff0c;通过describe查看具体原因 ~]# kubectl describe pod calico-node-pzlfv -n kube-system通过describe查看得知报错 Warning FailedScheduling 58s (x23 over 23m) default-sche…

基于YOLOv8/YOLOv7/YOLOv6/YOLOv5的扑克牌识别软件(Python+PySide6界面+训练代码)

摘要&#xff1a;开发扑克牌识别软件对于智能辅助决策工具的建立具有关键作用。本篇博客详细介绍了如何运用深度学习构建一个扑克牌识别软件&#xff0c;并提供了完整的实现代码。该系统基于强大的YOLOv8算法&#xff0c;并对比了YOLOv7、YOLOv6、YOLOv5&#xff0c;展示了不同…

mysql报错Deadlock found when trying to get lock; try restarting transaction处理

参考&#xff1a; https://blog.csdn.net/a1k2l45k/article/details/128220585 http://www.04007.cn/article/347.html https://www.jb51.net/python/296131kjw.htm show engine innodb status 查看日志&#xff0c;改代码。

tomcat配置好了,进不去这两个路径要一样

tomcat配置好了&#xff0c;进不去这两个路径要一样

原生JavaScript,根据后端返回扁平JSON动态【动态列头、动态数据】生成表格数据

前期准备&#xff1a; JQ下载地址&#xff1a; https://jquery.com/ <!DOCTYPE html> <html><head><meta charset"utf-8"><title>JSON动态生成表格数据,动态列头拼接</title><style>table {width: 800px;text-align: cen…

【RepVGG网络】

RepVGG网络 RepVGG网络是2021年由清华大学、旷视科技与香港科技大学等机构的研究者提出的一种深度学习模型结构&#xff0c;其核心特点是通过“结构重参数化”&#xff08;re-parameterization&#xff09;技术&#xff0c;在训练阶段采用复杂的多分支结构以优化网络的训练过程…

中间件MQ面试题之Rabbitmq

Rabbitmq 面试题 (1)RabbitMQ 如何确保消息不丢失? 消息持久化,当然前提是队列必须持久化 RabbitMQ确保持久性消息能从服务器重启中恢复的方式是,将它们写入磁盘上的 —个持久化日志文件,当发布一条持久性消息到持久交换器上时,RabbitMQ会在消 息提交到日志文件后才发…

stm32的EXTI的初始化-学习笔记

简介&#xff1a; 最近在学习stm32外设的过程中&#xff0c;学到EXTI这个外设的时候&#xff0c;感觉有点复杂&#xff0c;虽然是hal库开发&#xff0c;但是不明白所以&#xff0c;所以跟着也野火的教程&#xff0c;一遍看寄存器&#xff0c;一边看hal库的例子&#xff0c;写一…

web学习笔记(三十)

目录 1.jQuery选择器 2. jQuery祖宗的相关方法 3.jQuery子代的相关方法 4.jQuery同胞的相关方法 5.jQuery的class类操作 6.jQuery动画 6.1显示show()和hide() 6.2滑入slideDown()和滑出slideUp() 6.3淡入fadeIn()和淡出fadeOut() 7.自定义动画 animate() 1.jQuery选…

QT使用RabbitMQ

文章目录 1.RabbitMQ 客户端下载地址:1.1RabbitMQ基本结构:2.搭建RabbitMQ server3.安装步骤4.运行4.1 报错问题解决5.使用5.1 配置Web管理界面6.常用命令总结7.Qt客户端编译7.1 这里重点强调一下,这个文件需要改成静态库7.2 下载地址:(qamqp自己下载,下载成功后,静态编译…

如何解决循环依赖

在Spring框架中&#xff0c;Bean的创建与管理是通过Spring容器进行的&#xff0c;而Spring容器在创建和管理Bean时使用了三级缓存&#xff08;three-level cache&#xff09;机制&#xff0c;以提高性能并避免重复创建相同的Bean。这三级缓存分别是singletonObjects、earlySing…

Linux 安装使用 Docker

目录 一、前提卸载命令&#xff1a;执行情况&#xff1a; 二、安装 Docker1. 通过仓库进行安装&#xff08;在线方式&#xff09;1.1 设置存储库1.2 查看可安装版本1.3 安装 Docker1.4 启动 Docker1.5 验证是否成功 2. 通过 RMP 包安装&#xff08;离线方式&#xff09;2.2 安装…

Echarts+Vue 首页大屏静态示例Demo 第四版 支持自适应

效果: 源码: <template><ScaleScreenclass="scale-wrap":selfAdaption="true":autoScale="true":class="{ fullscreen-container: isFullScreen }"><div class="bg"><dv-loading v-if="loading&…

SeaTunnel-web in K8S

下载&#xff0c;官网下载有问题&#xff0c;上dlcdn.apache.org下载 https://dlcdn.apache.org/seatunnel/seatunnel-web/1.0.0/apache-seatunnel-web-1.0.0-bin.tar.gz apache-seatunnel-2.3.3中执行bin/install-plugin.sh下载connectors 下载web的源码 https://github.co…

LeetCode - 和为K的子数组

LCR 010. 和为 K 的子数组 看到这道题的时候&#xff0c;感觉还挺简单的&#xff0c;找到数组中和为k的连续子数组的个数&#xff0c;无非就是一个区间减去另一个区间的和等于k&#xff0c;然后想到了用前缀和来解决这道问题。再算连续子数组出现的个数的时候&#xff0c;可以使…

系统学习Python——装饰器:“私有“和“公有“属性案例-[使用伪私有、破坏私有和装饰器权衡]

分类目录&#xff1a;《系统学习Python》总目录 使用伪私有 除了泛化&#xff0c;这个版本还使用了Python的_X伪私有保持不变混合功能&#xff0c;通过将这个类的名称自动作为其前缀&#xff0c;就可以把wrapped属性局部化为代理控制类的变量。这避免了上一版本与一个真实的被…

DJI RONIN 4D变0字节恢复案例

RONIN 4D这个产品听起来比较陌生&#xff0c;还是DJI大疆出品。没错&#xff0c;这是大疆进军影视级的重点明星机型。前阵子刚处理过大疆RONIN 4D的修复案例&#xff0c;下边这个案例是和exfat有关的老问题:文件长度变成0字节。 故障存储:希捷18T /MS Exfat文件系统。 故障现…

uniapp实现点击选项跳转到应用商店进行下载

uni-app 中如何打开外部应用&#xff0c;如&#xff1a;浏览器、淘宝、AppStore、QQ等 https://ask.dcloud.net.cn/article/35621 Android唤起应用商店并跳转到应用详情页 兼容处理多个应用商店的情况 https://juejin.cn/post/6896399353301516295 如何查看market://detail…