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

相关文章

C语言中联合体union的使用

本文编辑整理自: http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=179471 一、前言 “联合体”(union)与“结构体”(struct)有一些相似之处。但两者有本质上的不同。在结构体中,各成员有各自的内存空间, 一个结构变量的总长度是各成员长度之和。而在“联合”中,各成员共享一段内存空间, 一个联合变量

Tolua使用笔记(上)

目录   1.准备工作 2.运行例子 01.HelloWorld:在C#中,创建和销毁Lua虚拟机 和 简单调用。 02.ScriptsFromFile:在C#中,对一个lua文件的执行调用 03.CallLuaFunction:在C#中,对lua函数的操作 04.AccessingLuaVariables:在C#中,对lua变量的操作 05.LuaCoroutine:在Lua中,

Vim使用基础篇

本文内容大部分来自 vimtutor,自带的教程的总结。在终端输入vimtutor 即可进入教程。 先总结一下,然后再分别介绍正常模式,插入模式,和可视模式三种模式下的命令。 目录 看完以后的汇总 1.正常模式(Normal模式) 1.移动光标 2.删除 3.【:】输入符 4.撤销 5.替换 6.重复命令【. ; ,】 7.复制粘贴 8.缩进 2.插入模式 INSERT

Lipowerline5.0 雷达电力应用软件下载使用

1.配网数据处理分析 针对配网线路点云数据,优化了分类算法,支持杆塔、导线、交跨线、建筑物、地面点和其他线路的自动分类;一键生成危险点报告和交跨报告;还能生成点云数据采集航线和自主巡检航线。 获取软件安装包联系邮箱:2895356150@qq.com,资源源于网络,本介绍用于学习使用,如有侵权请您联系删除! 2.新增快速版,简洁易上手 支持快速版和专业版切换使用,快速版界面简洁,保留主

如何免费的去使用connectedpapers?

免费使用connectedpapers 1. 打开谷歌浏览器2. 按住ctrl+shift+N,进入无痕模式3. 不需要登录(也就是访客模式)4. 两次用完,关闭无痕模式(继续重复步骤 2 - 4) 1. 打开谷歌浏览器 2. 按住ctrl+shift+N,进入无痕模式 输入网址:https://www.connectedpapers.com/ 3. 不需要登录(也就是

Toolbar+DrawerLayout使用详情结合网络各大神

最近也想搞下toolbar+drawerlayout的使用。结合网络上各大神的杰作,我把大部分的内容效果都完成了遍。现在记录下各个功能效果的实现以及一些细节注意点。 这图弹出两个菜单内容都是仿QQ界面的选项。左边一个是drawerlayout的弹窗。右边是toolbar的popup弹窗。 开始实现步骤详情: 1.创建toolbar布局跟drawerlayout布局 <?xml vers

C#中,decimal类型使用

在Microsoft SQL Server中numeric类型,在C#中使用的时候,需要用decimal类型与其对应,不能使用int等类型。 SQL:numeric C#:decimal

探索Elastic Search:强大的开源搜索引擎,详解及使用

🎬 鸽芷咕:个人主页  🔥 个人专栏: 《C++干货基地》《粉丝福利》 ⛺️生活的理想,就是为了理想的生活! 引入 全文搜索属于最常见的需求,开源的 Elasticsearch (以下简称 Elastic)是目前全文搜索引擎的首选,相信大家多多少少的都听说过它。它可以快速地储存、搜索和分析海量数据。就连维基百科、Stack Overflow、

flask 中使用 装饰器

因为要完成毕业设计,我用到fountain code做数据恢复。 于是在github上下载了fountain code的python原代码。 github上的作者用flask做了fountain code的demo。 flask是面向python的一个网站框架。 里面有用到装饰器。 今天笔试的时候,我也被问到了python的装饰器。

mathematica的使用

因为做实验用到Bloom filter这一技术,Bloom filter里面的数学公式可以用来画图。 那么用什么画图软件比较好呢? 当然是Mathematica啦。 利用代码Plot[{y=x},{x,0,100}] 就可以画出比较好的图 简直nice