美文网首页
OkHttp 加强版

OkHttp 加强版

作者: f8d1cf28626a | 来源:发表于2024-11-01 01:43 被阅读0次
class OkHttpForManager {

     internal class Notify {

         companion object {

             suspend fun get(url: String):Any {
                 val httpClient = OkHttpClient()
                 val request = Request.Builder().url(url).build()
                 val nothing = httpClient.newCall(request).execute().use {
                     if (!it.isSuccessful) throw IOException("\"Unexpected code $it\"")
                     return it
                 }
             }

             suspend fun post(name: String,value: String,toUrl:String):Any{
                 val httpClient = OkHttpClient()
                 val body:FormBody = FormBody.Builder().add(name,value).build()
                 val request = Request.Builder().url(toUrl).post(body).build()
                 val nothing = httpClient.newCall(request).execute().use {
                     if (!it.isSuccessful) throw IOException("\"Unexpected code $it\"")
                     return it
                 }
             }

             // 上传文件
             suspend fun update(filePath:String,fileName:String,toUrl:String,name: String? = null,value: String? = null):Any{
                 val httpClient = OkHttpClient()
                 // 如果需要上传文件,使用add方法的重载版本,传入文件路径
                 val file = File(filePath,fileName)
                 val body = file.asRequestBody("text/x-markdown; charset=utf-8".toMediaTypeOrNull())
                 val request = Request.Builder().url(toUrl).post(body).build()
                 val nothing = httpClient.newCall(request).execute().use {
                     if (!it.isSuccessful) throw IOException("\"Unexpected code $it\"")
                     return it
                 }
                 // 另外:最终请求网络返回的结果就是我们text文件中的内容
             }

             // 下载文件 (比如:下载一张图片)
             suspend fun download(toUrl:String,filePath: String? = null,fileName:String? = null):Any{
                 val httpClient = OkHttpClient()
                 val request = Request.Builder().url(toUrl).build()
                 val nothing = httpClient.newCall(request).execute().use {
                     if (!it.isSuccessful) throw IOException("\"Unexpected code $it\"")
                     // 将图片数句用流的方式写进文件中
                     if (filePath == null || fileName == null) return it

                     try {
                         val inputStream = it.body?.byteStream()
                         var outputStream:FileOutputStream? = null
                         val file = File(filePath,"hong.jpg")

                         if (null != file ) {
                             outputStream = FileOutputStream(file)
                             var buffer = ByteArray(1024)
                             var len:Int = 0
                             while (inputStream?.read(buffer) != -1) {
                                 len = inputStream?.read(buffer)!!
                                 outputStream.write(buffer,0,len)
                             }
                             outputStream.flush()
                         }
                     }
                     catch (ex:IOException) {
                         Log.d("download","IOException")
                         ex.printStackTrace()
                     }
                     return it
                 }
             }

             // 异步上传 Multipart 文件
             fun updateForMultipart(toUrl:String,fileParh:String? = null,any:Any? = null):Any{
                 val mType = "image/png".toMediaTypeOrNull()
                 val mBody = MultipartBody.Builder().addFormDataPart("title","password")
                     .addFormDataPart("image","hong",File(fileParh).asRequestBody(mType))
                     .build()
                 val request = Request.Builder()
                     .header("Authorization","Client-ID" + "...")
                     .url(toUrl)
                     .post(mBody)
                     .build()
                 val what = OkHttpClient().let {
                     it.newCall(request).execute().use {
                         if (!it.isSuccessful) throw IOException("\"Unexpected code $it\"")
                         return it
                     }
                 }
             }

             // 设置超时和缓存
             fun settingTimeOutAndCache(filePath:String):OkHttpClient{
                 val file = File(filePath)
                 val cacheSize:Long = 10 * 1024 * 1024
                 val cacheOfHong = Cache(file.absoluteFile,cacheSize)
                 val httpClient = OkHttpClient.Builder()
                     .connectTimeout(15,TimeUnit.SECONDS)
                     .writeTimeout(20,TimeUnit.SECONDS)
                     .readTimeout(20,TimeUnit.SECONDS)
                     .cache(cacheOfHong)
                     .build()
                 return httpClient
             }

             // 取消请求
             suspend fun cancelRequest(toUrl: String):Any{
                 val executor = Executors.newCachedThreadPool()
                 val coroutineScope = CoroutineScope(executor.asCoroutineDispatcher())
                 val request = Request.Builder().url(toUrl).cacheControl(CacheControl.FORCE_CACHE).build()
                 val call = OkHttpClient().newCall(request)
                 val nothing = coroutineScope.launch {
                     delay(100) // 100ms后取消
                     call.cancel()
                     // 确保JVM在协程执行完毕后退出
                     coroutineScope.coroutineContext.cancelChildren()
                     executor.shutdown()
                 }.join()

                 call.execute().use {
                     if (!it.isSuccessful) throw IOException("\"Unexpected code $it\"")
                     return it
                 }
             }
         }
     }
}
  • 使用
class UseForOkHttp {
    init {
        runBlocking {
            val what = OkHttpForManager.Notify.get("www.xxxhong.com").let {
                // 这里是请求回来的数据 it
                withContext(Dispatchers.Main) {
                    // 这里是协程 this
                    // 啥也不说了,刷新UI
                }
            }
        }
    }
}

在写代码,在写诗,也在写一段故事...

thank..

相关文章

网友评论

      本文标题:OkHttp 加强版

      本文链接:https://www.haomeiwen.com/subject/rypidjtx.html