赞
踩
OkHttp是一个开源的HTTP客户端库,用于在Java和Kotlin应用程序中进行网络请求和处理响应。它由Square开发,提供了简单、高效且易于使用的API。
网络请求
<uses-permission android:name="android.permission.INTERNET"/>
依赖库
// define a BOM and its version
implementation(platform("com.squareup.okhttp3:okhttp-bom:4.11.0"))
// define any required OkHttp artifacts without version
implementation("com.squareup.okhttp3:okhttp")
implementation("com.squareup.okhttp3:logging-interceptor")
同步请求不应在主线程进行
val client=OkHttpClient() fun get(){//网络请求主体 Thread(Runnable { // 构建请求主体 val request:Request=Request.Builder() .url(BASE_URL) .build() // 构建请求对象 val call:Call= client.newCall(request) // 发起同步请求execute--同步执行 val response:Response=call.execute() val body:String ?=response.body?.string() Log.v("mainokk","$body") }).start() }
val client=OkHttpClient() fun getAsync(){//网络请求主体 val request:Request=Request.Builder() .url(BASE_URL) .build() // 构建请求对象 val call:Call= client.newCall(request) // 发起同步请求execute--同步执行 call.enqueue(object :Callback{ override fun onFailure(call: Call, e: IOException) { TODO("Not yet implemented") } override fun onResponse(call: Call, response: Response) { val body:String ?=response.body?.string() Log.v("mainokk","$response") } }) }
异步请求的步骤和同步请求类似,只是调通了call的enquene方法异步请求,结果通过回调callback的onResponse方法和onFailure方法处理
基本流程都是先创建一个okHttpClient对象,然后通过Request.Builder()创建一个Request对象,OkHttpClient对象调用newCall()并传入Request对象就能获得一个call对象
区别在于execute()和enquene()方法的调用,调用execute()为同步请求并返回Response对象
调用enquene()方法测试通过callback的形式返回Response对象
POST请求与GET请求不同的地方在于Request。Builder的post()方法,post()方法需要一个RequestBody的对象作为参数
val client=OkHttpClient()
fun post(){
Thread(Runnable{
val body:FormBody=FormBody.Builder()
.add("","")
.build()
val request =Request.Builder().url(BASE_URL)
.post(body)
.build()
val call:Call= client.newCall(request)
val response:Response=call.execute()
Log.v("mainokk","$response")
})
}
val client=OkHttpClient() fun postAsync(){//网络请求主体 val body:FormBody=FormBody.Builder() .add("","") .build() val request:Request=Request.Builder() .url(BASE_URL) .post(body) .build() val call:Call= client.newCall(request) call.enqueue(object :Callback{ override fun onFailure(call: Call, e: IOException) { TODO("Not yet implemented") } override fun onResponse(call: Call, response: Response) { val body:String ?=response.body?.string() Log.v("mainokk","${response.body?.string()}") } }) }
拦截器是OkHttp当中一个比较强大的机制,可以监视,重写和重试调用请求
这是一个比较简单的Interceptor的实现,对请求的发送和响应进行了一些信息输出
class loggingInterceptor:Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val time_start:Long=System.nanoTime() val request=chain.request() val response=chain.proceed(request) val buffer= Buffer() request.body?.writeTo(buffer) val resquestBodyStr:String=buffer.readUtf8() Log.e("OKHTTP",String.format("")) val bussinessData=response.body?.string()?:"response" val mediaType=response.body?.contentType() val newBody=ResponseBody.create(mediaType,bussinessData) val newResponse=response.newBuilder().body(newBody).build() val time_end:Long=System.nanoTime() Log.e("OKHTTP",String.format("")) return newResponse } }
使用
val client=OkHttpClient.Builder()
.addInterceptor(loggingInterceptor())
.build()
以下是OkHttp中的五个重要的拦截器:
这些拦截器可以按照一定的顺序组合在一起,以实现不同的功能和逻辑
如果想要成为架构师或想突破20~30K薪资范畴,那就不要局限在编码,业务,要会选型、扩展,提升编程思维。此外,良好的职业规划也很重要,学习的习惯很重要,但是最重要的还是要能持之以恒,任何不能坚持落实的计划都是空谈。
如果你没有方向,这里给大家分享一套由阿里高级架构师编写的《Android八大模块进阶笔记》,帮大家将杂乱、零散、碎片化的知识进行体系化的整理,让大家系统而高效地掌握Android开发的各个知识点。

相对于我们平时看的碎片化内容,这份笔记的知识点更系统化,更容易理解和记忆,是严格按照知识体系编排的。
欢迎大家一键三连支持,若需要文中资料,直接扫描文末CSDN官方认证微信卡片免费领取↓↓↓(文末还有ChatGPT机器人小福利哦,大家千万不要错过)

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。