1.配置gradle
????implementation("com.squareup.okhttp3:okhttp:4.9.1")
2.异步GET请求
private fun asyncGet() {
val url = ""
//创建request请求对象
val request = Request.Builder()
.url(url)
//.method()方法与.get()方法选取1种即可
.method("GET", null)
.build()
//创建call并调用enqueue()方法实现网络请求
OkHttpClient().newCall(request)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
}
override fun onResponse(call: Call, response: Response) {
}
})
}
3.异步POST请求
private fun asyncPost() {
val url = ""
//添加post请求参数
val requestBody = FormBody.Builder()
.add("userName", "name")
.add("passWord", "pass")
.build()
//创建request请求对象
val request = Request.Builder()
.url(url)
.post(requestBody)
.build()
//创建call并调用enqueue()方法实现网络请求
OkHttpClient().newCall(request)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
}
override fun onResponse(call: Call, response: Response) {
}
})
}
4.异步上传文件?
private fun asyncUploadFile() {
val url = ""
//创建file
val filePath = Environment.getExternalStorageDirectory().absolutePath
val file = File(filePath, "test.txt")
//创建request请求对象
val request = Request.Builder()
.url(url)
.post(file.asRequestBody("text/txt; charset=utf-8".toMediaType()))
.build()
//创建call并调用enqueue()方法实现网络请求
OkHttpClient().newCall(request)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
}
override fun onResponse(call: Call, response: Response) {
}
})
}
5.异步下载文件?
private fun asyncDownloadFile() {
val url = ""
//创建request请求对象
val request = Request.Builder()
.url(url)
.build()
//创建call并调用enqueue()方法实现网络请求
OkHttpClient().newCall(request)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
}
override fun onResponse(call: Call, response: Response) {
//响应成功后,从response获取输入流,写入到文件中
val inputStream=response.body!!.byteStream()
val filePath=Environment.getExternalStorageDirectory().absolutePath
val file=File(filePath,"test.txt")
val fileOutputStream=FileOutputStream(file)
val buffer=ByteArray(2048)
do {
val len=inputStream.read(buffer)
fileOutputStream.write(buffer,0,len)
}while (len!=-1)
fileOutputStream.flush()
}
})
}
6.异步上传Multipart文件
private fun asyncUploadMultipart() {
val url = ""
//创建MultipartBody
val requestBody=MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title","img")
.addFormDataPart("image","test.png",RequestBody.create("image/png".toMediaType(),File("/sdcard/test.png")))
.build()
//创建request请求对象
val request = Request.Builder()
.url(url)
.post(requestBody)
.build()
//创建call并调用enqueue()方法实现网络请求
OkHttpClient().newCall(request)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
}
override fun onResponse(call: Call, response: Response) {
}
})
}
7.设置超时时间和缓存
private fun setTimeoutAndCache() {
val cacheDir=externalCacheDir
val cacheSize=10*1024*1024L
val okHttpClientBuilder=OkHttpClient.Builder()
.connectTimeout(20,TimeUnit.SECONDS)
.readTimeout(20,TimeUnit.SECONDS)
.writeTimeout(20,TimeUnit.SECONDS)
.cache(Cache(File(cacheDir,"cache.txt"),cacheSize))
val okHttpClient=okHttpClientBuilder.build()
}
|