Kotlin OKHTTP3和拦截器的使用

2024-03-13 05:36

本文主要是介绍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}}

这篇关于Kotlin OKHTTP3和拦截器的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/803793

相关文章

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

windows和Linux使用命令行计算文件的MD5值

《windows和Linux使用命令行计算文件的MD5值》在Windows和Linux系统中,您可以使用命令行(终端或命令提示符)来计算文件的MD5值,文章介绍了在Windows和Linux/macO... 目录在Windows上:在linux或MACOS上:总结在Windows上:可以使用certuti

CentOS和Ubuntu系统使用shell脚本创建用户和设置密码

《CentOS和Ubuntu系统使用shell脚本创建用户和设置密码》在Linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设置密码,本文写了一个shell... 在linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地