网络请求在安卓开发中非常常见,写一个工具类能有效的节省开发时间提高效率,这里就分享一下,有不足的请斧正
引入
implementation("com.squareup.okhttp3:okhttp:4.2.1")
需要的权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
Kotlin版本
import android.os.Environment
import com.epuxun.drink.utli.application
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okio.BufferedSink
import java.io.BufferedInputStream
import java.io.File
import java.io.IOException
import java.util.*
import java.util.concurrent.TimeUnit
object HttpHelper {
private const val MEDIA_TYPE = "application/json; charset=utf-8"
private const val MAX_CACHE_SIZE = 1024 * 1024 * 50L// 50M 的缓存大小
private const val DEFAULT_TIMEOUT = 15L
/**
* 获取 OkHttpClient
*/
private fun getOkHttpClient(): OkHttpClient {
val builder = OkHttpClient().newBuilder()
val cacheFile = File(application.cacheDir, "cache")
val cache = Cache(cacheFile, MAX_CAC