首先导入okhttp的包:
implementation 'com.squareup.okhttp3:okhttp:4.2.0'
现在kotlin用的人越来越多了.真好.因为kt的版本一直在更新着,我现在用的是1.3.72的
之下代码还是需要一些kt的基础的要不然会有点难理解
首先创建okhttp的一个实例对象
private class ZTrustManager : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
}
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
}
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
}
private val cookieStore by lazy {
HashMap<HttpUrl?, List<Cookie>>()
}
// 就在这里实例化okhttp 其他的东西用到即可添加.用不到注释掉也无大碍.
private val mOkHttpClient by lazy {
OkHttpClient().newBuilder().apply {
this.connectTimeout(40, TimeUnit.SECONDS)
this.readTimeout(40, TimeUnit.SECONDS)
this.writeTimeout(40, TimeUnit.SECONDS)
// 如果后台需要用到cookie 就加上就可以
cookieJar(object : CookieJar {
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val cookies: List<Cookie>? =
cookieStore.get(CloudUrlIinterface.url.toHttpUrlOrNull())
if (cookies == null) {
// println("没加载到cookie")
}
return cookies ?: ArrayList()
}
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
cookieStore.put(url, cookies)
cookieStore.put(CloudUrlIinterface.url.toHttpUrlOrNull(), cookies)
/*for (cookie in cookies) {
println("guo cookice name:" + cookie.name)
println("guo cookece path:" + cookie.path)
}*/
}
})
///
val trustAllCerts: Array<TrustManager> = arrayOf(ZTrustManager())
val sslContext: SSLContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory
sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
hostnameVerifier(HostnameVerifier { _: String?, _: SSLSession? -> true })
}.build()
}
GET请求,只有带url的那种…
fun getAsync(url: String, callback: ResultCallback<*>) {
val request = Request.Builder()
.url(url)
.build()
deliverResult(callback, request)
}
GET请求,需要用到token
/**
* get 只带token(放headers中)
* @param headerMap token
*/
fun getAsync(
url: String,
headerMap: Map<String, String>,
callback: ResultCallback<*>
) {
// okhttp get 请求添加参数
val request = Request.Builder()
.url(url)
.addHeaderMap(headerMap)
.build()
deliverResult(callback, request)
}
GET请求,只带参数,拼接的那种
/**
* get 只带参数
* @param hashMap 参数列表
*/
fun getAsync(
url: String,
params: HashMap<String, String>,
callback: ResultCallback<*>
) {
// okhttp get 请求添加参数
val urlBuilder = url.toHttpUrlOrNull()?.newBuilder()
?.apply {
addQueryParamMap(params)
}
val request = Request.Builder()
.url(urlBuilder!!.build())
.build()
deliverResult(callback, request)
}
GET请求,token,拼接参数
/**
* get 带参数请求,带token
* @param hashMap 参数列表
* @param headerMap token
*/
fun getAsync(
url: String,
hashMap: HashMap<String, String>,
headerMap: Map<String, String>,
callback: ResultCallback<*>
) {
// okhttp get 请求添加参数
val urlBuilder = url.toHttpUrlOrNull()?.newBuilder()
?.apply {
addQueryParamMap(hashMap)
}
val request = Request.Builder()
.url(urlBuilder!!.build())
.addHeaderMap(headerMap)
.build()
deliverResult(callback, request)
}
/**
* put 带参数请求,带token
* @param hashMap 参数列表(参数form-body请求)
* @param headerMap token
*/
fun putAsync(
url: String,
hashMap: HashMap<String, String>,
headerMap: Map<String, String>,
callback: ResultCallback<*>
) {
val body = FormBody.Builder().apply {
addHeaderMap(hashMap)
}.build()
val request = Request.Builder()
.url(url)
.put(body)
.addHeaderMap(headerMap)
.build()
deliverResult(callback, request)
}
private val jsonType get() = "application/json; charset=utf-8".toMediaTypeOrNull()
/**
* post 带参数,(raw请求方式)
* 带token
*/
fun postAsync(
url: String,
headerMap: Map<String, String>,
jsonObject: JSONObject,
callback: ResultCallback<*>
) {
val body: RequestBody = jsonObject.toString().toRequestBody(jsonType)
val request: Request = Request
.Builder()
.url(url)
.addHeaderMap(headerMap)
.post(body)
.build()
deliverResult(callback, request)
}
PUT请求方式
/**
* put请求 带参数,带token(参数row请求方式)
*/
fun putAsync(
url: String,
jsonObject: JSONObject,
headerMap: Map<String, String>,
callback: ResultCallback<*>
) {
val body: RequestBody = jsonObject.toString().toRequestBody(jsonType)
val request = Request.Builder()
.url(url)
.addHeaderMap(headerMap)
.put(body)
.build()
deliverResult(callback, request)
}
DELETE请求
/**
* delete
* 带参数,带token
*/
fun deleteAsync(
url: String,
paramMap: HashMap<String, String>,
headerMap: Map<String, String>,
callback: ResultCallback<*>
) {
val body = FormBody.Builder().apply {
addHeaderMap(paramMap)
}.build()
val request: Request = Request
.Builder()
.url(url)
.addHeaderMap(headerMap)
.delete(body)
.build()
deliverResult(callback, request)
}
其他在请求中用到的几个东西
集中在这里做了请求回调的处理
deliverResult()
private fun deliverResult(callback: ResultCallback<*>, request: Request) {
mOkHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
sendFailureStringCallback(request, e, callback)
}
override fun onResponse(call: Call, response: Response) {
sendSuccessResultCallback(response, callback as ResultCallback<Any>)
}
})
}
// 创建一个单例的handler,发送在主线程的.
private val mHandler by lazy {
Handler(Looper.getMainLooper())
}
fun sendFailureStringCallback(
request: Request,
exception: Exception,
callback: ResultCallback<*>
) {
// 这里回调在主线程
mHandler.post {
callback.onError(request, exception)
}
}
/**
* 这里就不在这里回调到主线程,前面做处理把
*/
fun sendSuccessResultCallback(mObject: Any, callback: ResultCallback<Any>) {
callback.onResponse(mObject)
}
回调类,也就是在网络请求下来的用到的callback
import com.google.gson.internal.`$Gson$Types`
import okhttp3.Request
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
/**
* Created by Android Studio.
* User: GGY
* Date: 2020/10/21
*/
abstract class ResultCallback<T> {
val mType: Type by lazy {
getSuperclassTypeParameter(javaClass)
}
companion object {
fun getSuperclassTypeParameter(subclass: Class<*>): Type {
val superclass = subclass.genericSuperclass
if (superclass is Class<*>) {
throw RuntimeException("Miss type parameter.")
}
val parameterizedType = superclass as ParameterizedType
return `$Gson$Types`.canonicalize(parameterizedType.actualTypeArguments[0])
}
}
abstract fun onError(request: Request, exception: Exception)
abstract fun onResponse(response: T)
}
可能你在使用的过程对这些函数产生了疑惑
addHeaderMap(),addQueryParamMap(),为什么我调用不到呢?
这里我为了方便简写在请求中添加map(参数)写了几个扩展函数
//写接口扩展函数, 方便在做请求的时候,直接可以传入Map类型
private fun Request.Builder.addHeaderMap(
headerMap: Map<String, String>
): Request.Builder {
headerMap.forEach { key, token ->
this.addHeader(key, token)
}
return this
}
private fun FormBody.Builder.addHeaderMap(
headerMap: Map<String, String>
): FormBody.Builder {
headerMap.forEach { key, token ->
this.add(key, token)
}
return this
}
private fun HttpUrl.Builder.addQueryParamMap(headerMap: HashMap<String, String>): HttpUrl.Builder {
headerMap.forEach { key, value ->
this.addQueryParameter(key, value)
}
return this
}
在用raw请求的时候,JSONObject不会用的话,我也贴出来把,不过都会用把…
val jsonObject = JSONObject()
jsonObject.put("device_code", deviceCode)
jsonObject.put("is_online", isOnlie)
基本把整个类都贴完了.这也是我用到的几种请求方式.写的方式可能有些不雅,不过不要担心,人都是要慢慢成长的.理解了代码等你写出来肯定会比我强.一起加油把.