android superclass type 添加,android kt开发, okhttp网络请求

本文详细介绍了如何在Kotlin中使用OkHttp进行网络请求,包括GET、POST、PUT、DELETE等操作,并展示了如何处理超时、SSL证书以及回调函数。还提供了自定义的ResultCallback回调类,以及如何添加请求头和参数。此外,还分享了一些实用的扩展函数,简化了代码的编写。
摘要由CSDN通过智能技术生成

首先导入okhttp的包:

implementation 'com.squareup.okhttp3:okhttp:4.2.0'1

现在kotlin用的人越来越多了.真好.因为kt的版本一直在更新着,我现在用的是1.3.72的

之下代码还是需要一些kt的基础的要不然会有点难理解

首先创建okhttp的一个实例对象

private class ZTrustManager : X509TrustManager { override fun checkClientTrusted(chain: Array?, authType: String?) { } override fun checkServerTrusted(chain: Array?, authType: String?) { } override fun getAcceptedIssuers(): Array = arrayOf() } private val cookieStore by lazy { HashMap>() }

// 就在这里实例化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 { val cookies: List? = cookieStore.get(CloudUrlIinterface.url.toHttpUrlOrNull()) if (cookies == null) { // println("没加载到cookie") } return cookies ?: ArrayList() } override fun saveFromResponse(url: HttpUrl, cookies: List) { 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 = 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() }1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

GET请求,只有带url的那种…

fun getAsync(url: String, callback: ResultCallback) { val request = Request.Builder() .url(url) .build() deliverResult(callback, request) }1

2

3

4

5

6

GET请求,需要用到token

/** * get 只带token(放headers中) * @param headerMap token */ fun getAsync( url: String, headerMap: Map, callback: ResultCallback ) { // okhttp get 请求添加参数 val request = Request.Builder() .url(url) .addHeaderMap(headerMap) .build() deliverResult(callback, request) }1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

GET请求,只带参数,拼接的那种

/** * get 只带参数 * @param hashMap 参数列表 */ fun getAsync( url: String, params: HashMap, callback: ResultCallback ) { // okhttp get 请求添加参数 val urlBuilder = url.toHttpUrlOrNull()?.newBuilder() ?.apply { addQueryParamMap(params) } val request = Request.Builder() .url(urlBuilder!!.build()) .build() deliverResult(callback, request) }1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

GET请求,token,拼接参数

/** * get 带参数请求,带token * @param hashMap 参数列表 * @param headerMap token */ fun getAsync( url: String, hashMap: HashMap, headerMap: Map, 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) }1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

POST请求,带token,请求方式为form-body

f2cedbc36212efbfba538ed806b62432.png

/** * put 带参数请求,带token * @param hashMap 参数列表(参数form-body请求) * @param headerMap token */ fun putAsync( url: String, hashMap: HashMap, headerMap: Map, callback: ResultCallback ) { val body = FormBody.Builder().apply { addHeaderMap(hashMap) }.build() val request = Request.Builder() .url(url) .put(body) .addHeaderMap(headerMap) .build() deliverResult(callback, request) }1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

POST请求方式,raw提交方式

9b50e040447f1e69f30e577aa7b3c8fa.png

private val jsonType get() = "application/json; charset=utf-8".toMediaTypeOrNull()1

/** * post 带参数,(raw请求方式) * 带token */ fun postAsync( url: String, headerMap: Map, 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) }1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

PUT请求方式

/** * put请求 带参数,带token(参数row请求方式) */ fun putAsync( url: String, jsonObject: JSONObject, headerMap: Map, callback: ResultCallback ) { val body: RequestBody = jsonObject.toString().toRequestBody(jsonType) val request = Request.Builder() .url(url) .addHeaderMap(headerMap) .put(body) .build() deliverResult(callback, request) }1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

DELETE请求

/** * delete * 带参数,带token */ fun deleteAsync( url: String, paramMap: HashMap, headerMap: Map, 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) }1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

其他在请求中用到的几个东西

集中在这里做了请求回调的处理

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) } }) }1

2

3

4

5

6

7

8

9

10

11

// 创建一个单例的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) { callback.onResponse(mObject) }1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

回调类,也就是在网络请求下来的用到的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 { 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)

}1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

可能你在使用的过程对这些函数产生了疑惑

addHeaderMap(),addQueryParamMap(),为什么我调用不到呢?

这里我为了方便简写在请求中添加map(参数)写了几个扩展函数

//写接口扩展函数, 方便在做请求的时候,直接可以传入Map类型

private fun Request.Builder.addHeaderMap( headerMap: Map

): Request.Builder { headerMap.forEach { key, token -> this.addHeader(key, token) } return this

}

private fun FormBody.Builder.addHeaderMap( headerMap: Map

): FormBody.Builder { headerMap.forEach { key, token -> this.add(key, token) } return this

}

private fun HttpUrl.Builder.addQueryParamMap(headerMap: HashMap): HttpUrl.Builder { headerMap.forEach { key, value -> this.addQueryParameter(key, value) } return this

}1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

在用raw请求的时候,JSONObject不会用的话,我也贴出来把,不过都会用把…

val jsonObject = JSONObject() jsonObject.put("device_code", deviceCode) jsonObject.put("is_online", isOnlie)1

2

3

基本把整个类都贴完了.这也是我用到的几种请求方式.写的方式可能有些不雅,不过不要担心,人都是要慢慢成长的.理解了代码等你写出来肯定会比我强.一起加油把.

文章来源: blog.csdn.net,作者:Gggggggyyy,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/ggy_yao/article/details/110089475

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值