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

相关文章

Linux中的计划任务(crontab)使用方式

《Linux中的计划任务(crontab)使用方式》:本文主要介绍Linux中的计划任务(crontab)使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、前言1、linux的起源与发展2、什么是计划任务(crontab)二、crontab基础1、cro

kotlin中const 和val的区别及使用场景分析

《kotlin中const和val的区别及使用场景分析》在Kotlin中,const和val都是用来声明常量的,但它们的使用场景和功能有所不同,下面给大家介绍kotlin中const和val的区别,... 目录kotlin中const 和val的区别1. val:2. const:二 代码示例1 Java

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat

C++中std::distance使用方法示例

《C++中std::distance使用方法示例》std::distance是C++标准库中的一个函数,用于计算两个迭代器之间的距离,本文主要介绍了C++中std::distance使用方法示例,具... 目录语法使用方式解释示例输出:其他说明:总结std::distance&n编程bsp;是 C++ 标准

vue使用docxtemplater导出word

《vue使用docxtemplater导出word》docxtemplater是一种邮件合并工具,以编程方式使用并处理条件、循环,并且可以扩展以插入任何内容,下面我们来看看如何使用docxtempl... 目录docxtemplatervue使用docxtemplater导出word安装常用语法 封装导出方

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

使用Python实现快速搭建本地HTTP服务器

《使用Python实现快速搭建本地HTTP服务器》:本文主要介绍如何使用Python快速搭建本地HTTP服务器,轻松实现一键HTTP文件共享,同时结合二维码技术,让访问更简单,感兴趣的小伙伴可以了... 目录1. 概述2. 快速搭建 HTTP 文件共享服务2.1 核心思路2.2 代码实现2.3 代码解读3.

Elasticsearch 在 Java 中的使用教程

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文... 目录1. Elasticsearch 简介2. 环境准备2.1 安装 Elasticsearch2.2 J

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当