当前位置:   article > 正文

Kotlin OKHTTP3和拦截器的使用

Kotlin OKHTTP3和拦截器的使用

注意:在android6.0以后网络请求还需如下配置:

 android:usesCleartextTraffic="true"

  1. <application
  2. android:allowBackup="true"
  3. android:icon="@mipmap/ic_launcher"
  4. android:label="@string/app_name"
  5. android:roundIcon="@mipmap/ic_launcher_round"
  6. android:supportsRtl="true"
  7. android:usesCleartextTraffic="true"
  8. android:theme="@style/AppTheme">
  9. ***
  10. </application>

一、引入okhttp3

  1. //okhttp3
  2. implementation("com.squareup.okhttp3:okhttp:4.9.0")
  3. implementation("com.squareup.okhttp3:logging-interceptor:4.9.0")

二、创建单例对象

  1. package com.example.buju.http
  2. import android.content.Context
  3. import android.os.Environment
  4. import android.util.Log
  5. import android.widget.Toast
  6. import okhttp3.Call
  7. import okhttp3.Callback
  8. import okhttp3.FormBody
  9. import okhttp3.MediaType.Companion.toMediaType
  10. import okhttp3.MultipartBody
  11. import okhttp3.OkHttpClient
  12. import okhttp3.Request
  13. import okhttp3.RequestBody
  14. import okhttp3.Response
  15. import org.json.JSONObject
  16. import java.io.File
  17. import java.io.IOException
  18. import java.util.concurrent.TimeUnit
  19. /**
  20. * 单例对象
  21. * -http请求工具类
  22. * */
  23. object HiOkhttp {
  24. /* private val client:OkHttpClient
  25. // 最早调用模块
  26. init {
  27. val httpLoggingInterceptor = HttpLoggingInterceptor()// okhttp3自带拦截器
  28. httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
  29. client = OkHttpClient.Builder()// builder构造者设计模式
  30. .connectTimeout(10,TimeUnit.SECONDS)//连接超时时间
  31. .readTimeout(10,TimeUnit.SECONDS)// 读取超时
  32. .writeTimeout(10,TimeUnit.SECONDS)// 写超时
  33. .addInterceptor(httpLoggingInterceptor)// 自带拦截器
  34. .build()
  35. }*/
  36. val client = OkHttpClient.Builder()// builder构造者设计模式
  37. .connectTimeout(10,TimeUnit.SECONDS)//连接超时时间
  38. .readTimeout(10,TimeUnit.SECONDS)// 读取超时
  39. .writeTimeout(10,TimeUnit.SECONDS)// 写超时
  40. .addInterceptor(LoggingInterceptor())// 自定义拦截器
  41. .build()
  42. // android 分为主线程和子线程
  43. // 主线程就是APP一启动后,咱们android framework层会启动一个线程,主线程(UI线程)
  44. // 子线程 - new Thread().start()
  45. /**
  46. * get请求
  47. * -同步请求不要放在主线程中执行,容易阻塞线程
  48. * */
  49. fun syncGet(url:String){
  50. // 构造请求体
  51. val request:Request = Request.Builder()
  52. .url(url)
  53. .build()
  54. // 构造请求对象
  55. val call:Call = client.newCall(request)
  56. Thread(Runnable {// 构建子线程
  57. // execute() - 发起同步请求(同步执行)
  58. val response:Response = call.execute()
  59. val body: String? = response.body?.string()
  60. Log.e("OKHTTP","get response:${body}")
  61. }).start()
  62. }
  63. /**
  64. * get请求
  65. * -异步请求
  66. * */
  67. fun asyncGet(url:String){
  68. // 构造请求体
  69. val request:Request = Request.Builder()
  70. .url(url)
  71. .build()
  72. // 构造请求对象
  73. val call:Call = client.newCall(request)
  74. // enqueue() - 发起异步请求(异步执行)
  75. call.enqueue(object :Callback{
  76. override fun onFailure(call: Call, e: IOException) {
  77. Log.e("OKHTTP","get onFailure:${e.message}")
  78. }
  79. override fun onResponse(call: Call, response: Response) {
  80. val body:String? = response.body?.string()
  81. Log.e("OKHTTP","get response:${body}")
  82. }
  83. })
  84. }
  85. /**
  86. * post请求
  87. * -同步表单请求,不要放在主线程中执行,容易阻塞线程
  88. * */
  89. fun syncPost(url:String){
  90. val body = FormBody.Builder()
  91. .add("userId","123")
  92. .add("userName","zs")
  93. .build()
  94. val request:Request = Request.Builder()
  95. .url(url)
  96. .post(body)
  97. .build()
  98. val call:Call = client.newCall(request)
  99. Thread(Runnable {
  100. val response:Response = call.execute()
  101. val resultBody = response.body?.string()
  102. Log.e("OKHTTP","post response:${resultBody}")
  103. }).start()
  104. }
  105. /**
  106. * post请求
  107. * -异步表单请求
  108. * */
  109. fun asyncPost(url:String){
  110. val body = FormBody.Builder()
  111. .add("userId","123")
  112. .add("userName","zs")
  113. .build()
  114. val request:Request = Request.Builder()
  115. .url(url)
  116. .post(body)
  117. .build()
  118. val call:Call = client.newCall(request)
  119. call.enqueue(object :Callback{
  120. override fun onFailure(call: Call, e: IOException) {
  121. Log.e("OKHTTP","post onFailure:${e.message}")
  122. }
  123. override fun onResponse(call: Call, response: Response) {
  124. val resultBody = response.body?.string()
  125. Log.e("OKHTTP","post response:${resultBody}")
  126. }
  127. })
  128. }
  129. /**
  130. * post请求
  131. * -异步多表单文件上传请求
  132. * -url必须支持文件上传的接口
  133. * -android6.0以后,读取外部存储卡的文件都是需要动态申请权限
  134. * */
  135. fun asyncPostMultipart(url:String,context:Context){
  136. val file = File(Environment.getExternalStorageDirectory(),"demo.png")
  137. if (!file.exists()){
  138. Toast.makeText(context,"文件不存在",Toast.LENGTH_LONG).show()
  139. return
  140. }
  141. val body = MultipartBody.Builder()
  142. .addFormDataPart("key1","value1")
  143. .addFormDataPart("key2","value2")
  144. .addFormDataPart("file",
  145. "file.png",
  146. RequestBody.create("application/octet-stream".toMediaType(), file))
  147. .build()
  148. val request:Request = Request.Builder()
  149. .url(url)
  150. .post(body)
  151. .build()
  152. val call:Call = client.newCall(request)
  153. call.enqueue(object :Callback{
  154. override fun onFailure(call: Call, e: IOException) {
  155. Log.e("OKHTTP","post onFailure:${e.message}")
  156. }
  157. override fun onResponse(call: Call, response: Response) {
  158. val resultBody = response.body?.string()
  159. Log.e("OKHTTP","post response:${resultBody}")
  160. }
  161. })
  162. }
  163. /**
  164. * post请求
  165. * -异步字符串请求
  166. * */
  167. fun asyncPostString(url:String){
  168. // 纯文本
  169. /* val textPlain = "text/plain;charset=utf-8".toMediaType()
  170. val textObj = "username:username;password:1234"
  171. val body = RequestBody.create(textPlain,textObj)*/
  172. // json对象
  173. val applicationJson = "application/json;charset=utf-8".toMediaType();
  174. val jsonObj = JSONObject()
  175. jsonObj.put("key1","val1")
  176. jsonObj.put("key2","val2")
  177. val body = RequestBody.create(applicationJson,jsonObj.toString())
  178. val request = Request.Builder()
  179. .url(url)
  180. .post(body)
  181. .build()
  182. val call:Call = client.newCall(request)
  183. call.enqueue(object :Callback{
  184. override fun onFailure(call: Call, e: IOException) {
  185. Log.e("OKHTTP","post onFailure:${e.message}")
  186. }
  187. override fun onResponse(call: Call, response: Response) {
  188. val resultBody = response.body?.string()
  189. Log.e("OKHTTP","post response:${resultBody}")
  190. }
  191. })
  192. }
  193. }

三、自定义okhttp3拦截器

  1. package com.example.buju.http
  2. import android.util.Log
  3. import okhttp3.Interceptor
  4. import okhttp3.Response
  5. import okhttp3.ResponseBody
  6. import okio.Buffer
  7. /**
  8. * OKHttp3 拦截器
  9. * */
  10. class LoggingInterceptor:Interceptor {
  11. override fun intercept(chain: Interceptor.Chain): Response {
  12. val time_start = System.nanoTime()// 开始时间戳
  13. val request = chain.request()// 请求
  14. val response = chain.proceed(request)// 响应
  15. /**
  16. * 获取请求信息
  17. * */
  18. val buffer = Buffer()// okio.Buffer
  19. request.body?.writeTo(buffer)
  20. val requestBodyStr = buffer.readUtf8()
  21. // request.url - 请求接口;requestBodyStr - 请求携带的参数
  22. Log.e("OKHTTP",String.format("Sending request %s with params %s",request.url,requestBodyStr))
  23. /**
  24. * 获取响应信息
  25. * */
  26. val bussinessData:String = response.body?.string()?:"response body null"
  27. val mediaType = response.body?.contentType()
  28. val newBody = ResponseBody.create(mediaType,bussinessData)
  29. val newResponse = response.newBuilder().body(newBody).build()
  30. val time_end = System.nanoTime()//结束始时间戳
  31. // request.url - 请求接口;(time_end - time_start) -执行时间;bussinessData - 响应数据
  32. Log.e("OKHTTP",String.format("Received response for %s in %.1fms >>> %s",request.url,(time_end - time_start),bussinessData))
  33. return newResponse
  34. }
  35. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/260019
推荐阅读
相关标签
  

闽ICP备14008679号