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
}
// 另外:最終請(qǐng)求網(wǎng)絡(luò)返回的結(jié)果就是我們text文件中的內(nèi)容
}
// 下載文件 (比如:下載一張圖片)
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\"")
// 將圖片數(shù)句用流的方式寫(xiě)進(jìn)文件中
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
}
}
}
// 設(shè)置超時(shí)和緩存
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
}
// 取消請(qǐng)求
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在協(xié)程執(zhí)行完畢后退出
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 {
// 這里是請(qǐng)求回來(lái)的數(shù)據(jù) it
withContext(Dispatchers.Main) {
// 這里是協(xié)程 this
// 啥也不說(shuō)了,刷新UI
}
}
}
}
}
在寫(xiě)代碼,在寫(xiě)詩(shī),也在寫(xiě)一段故事...
thank..