Skip to content

Commit

Permalink
✨ 网络请求工具类增加同步的api方法
Browse files Browse the repository at this point in the history
  • Loading branch information
stars-one committed May 7, 2023
1 parent 0dfaad1 commit 2d1a987
Showing 1 changed file with 90 additions and 3 deletions.
93 changes: 90 additions & 3 deletions src/main/kotlin/com/starsone/controls/utils/net/NetworkUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ object NetworkUtil {
}

/**
* 发起post请求(传统的表单)
* 发起post请求(传统的表单),异步
*
* @param url 接口地址
* @param data 数据HashMap
Expand Down Expand Up @@ -75,7 +75,35 @@ object NetworkUtil {
}

/**
* Post请求(传json数据)
* 发起post请求(传统的表单)
*
* @param url 接口地址
* @param data 数据HashMap
* @param headers 请求头 HashMap
*/
fun post(url: String, data: HashMap<String, out Any>, headers: HashMap<String, String>): Response {
//1.构造传参参数
val formBody = FormBody.Builder()
data.forEach { (t, v) ->
formBody.add(t, v.toString())
}
val formBodyData = formBody.build()
//2.构造request
val requestBuilder = Request.Builder()
.url(url)
.post(formBodyData)

//构造头部参数
headers.forEach { (t, u) ->
requestBuilder.addHeader(t, u)
}
val request = requestBuilder.build()
//3.发送请求
return sendRequest(request)
}

/**
* Post请求(传json数据) 异步
*
* @param T
* @param url
Expand All @@ -102,7 +130,33 @@ object NetworkUtil {
}

/**
* Get 请求
* Post请求(传json数据)
*
* @param T
* @param url
* @param data 实体类数据(会自动转为json字符串)
* @param headers 请求头
*/
fun postJson(url: String, data: Any, headers: HashMap<String, String>): Response {
//1.构造传参参数
val requestBody = gson.toJson(data).toRequestBody(JSON)

//2.构造request
val requestBuilder = Request.Builder()
.url(url)
.post(requestBody)

//构造头部参数
headers.forEach { (t, u) ->
requestBuilder.addHeader(t, u)
}
val request = requestBuilder.build()
//3.发送请求
return sendRequest(request)
}

/**
* Get 请求 异步
*
* @param url
* @param data 数据map,会自动拼接
Expand Down Expand Up @@ -130,6 +184,33 @@ object NetworkUtil {
sendRequest(request, callBack)
}

/**
* Get 请求
*
* @param url
* @param data 数据map,会自动拼接
* @param headers
*/
fun get(url: String, data: HashMap<String, out Any>, headers: HashMap<String, String>): Response {
//1.构造传参参数
val param = data.map { (t, u) ->
"""$t=$u"""
}.joinToString("&")

var finalUrl = url + param
if (!url.endsWith("?")) {
finalUrl = url + "?" + param
}
val builder = Request.Builder()
.url(finalUrl)
headers.forEach { (t, u) ->
builder.addHeader(t, u)
}
//2.构造request
val request = builder.get().build()
//3.发出请求
return sendRequest(request)
}

/**
* 发起网络请求
Expand Down Expand Up @@ -163,6 +244,12 @@ object NetworkUtil {
}


fun sendRequest(request: Request): Response {
return okHttpClient.newCall(request).execute()
}



/**
* 回调函数
*
Expand Down

0 comments on commit 2d1a987

Please sign in to comment.