1. OkHttp
OkHttp
是由 Square 公司開發(fā)的一個(gè) HTTP 客戶端庫(kù),用于在 Java 和 Android 中執(zhí)行網(wǎng)絡(luò)請(qǐng)求。它功能強(qiáng)大斗搞、性能高效指攒,并且支持各種高級(jí)特性,如連接池僻焚、請(qǐng)求緩存允悦、攔截器等。采用OkHttp
進(jìn)行簡(jiǎn)單的get
和post
請(qǐng)求示例:
object BoxHttp {
private const val BASEURL = "https://api.mocation.cc/api"
private val client: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
// .addInterceptor(LoggingInterceptor())
.build()
/**
* 同步GET方法
*/
fun getSync() {
Thread(kotlinx.coroutines.Runnable {
val request: Request = Request.Builder()
.url("${BASEURL}/coopen/data")
.build()
val call = client.newCall(request)
val response = call.execute()
val body = response.body?.string()
Log.e("okhttp", "收到了返回值:$body")
}).start()
}
/**
* 異步GET方法
*/
fun getAsync() {
val request = Request.Builder()
.url("https://api.mocation.cc/api/coopen/data")
.build()
Log.e("okhttp", "收到了 連接:${request.url}")
val call = client.newCall(request)
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e("okhttp", "收到了 異步 錯(cuò)誤返回值:${e.message}")
}
override fun onResponse(call: Call, response: Response) {
Log.e("okhttp", "收到了異步 返回值:${response.body?.string()}")
}
})
}
/**
* 同步POST方法
*/
fun postSync() {
Thread(kotlinx.coroutines.Runnable {
val body: FormBody = FormBody.Builder()
.build()
val request: Request = Request.Builder()
.url("${BASEURL}/article/23/like")
.post(body)
.build()
val call = client.newCall(request)
val response = call.execute()
val bodyR = response.body?.string()
Log.e("okhttp", "POST 收到了返回值:$bodyR")
}).start()
}
/**
* 異步POST方法
*/
fun postAsync() {
Log.e("okhttp","當(dāng)前線程2:${Thread.currentThread()}")
val body: FormBody = FormBody.Builder()
.build()
val httpUrl = "${BASEURL}/article/23/like"
Log.e("okhttp", "請(qǐng)求的Url:$httpUrl")
val request: Request = Request.Builder()
.url(httpUrl)
.post(body)
.build()
val call = client.newCall(request)
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e("okhttp","當(dāng)前線程3:${Thread.currentThread()}")
Log.e("okhttp", "收到了 POST 異步 錯(cuò)誤返回值:${e.message}")
}
override fun onResponse(call: Call, response: Response) {
Log.e("okhttp","當(dāng)前線程3:${Thread.currentThread()}")
Log.e("okhttp", "收到了 POST 異步 返回值:${response.body?.string()}")
}
})
}
}
在OkHttp中提供了強(qiáng)大的攔截器Interceptor
,我們可以在自定義的Interceptor中虑啤,對(duì)請(qǐng)求進(jìn)行修改或者對(duì)返回體進(jìn)行統(tǒng)一的一些處理隙弛,比如要在請(qǐng)求頭中添加通用的請(qǐng)求頭或者在返回體中進(jìn)行特殊錯(cuò)誤的判斷等
class LoggingInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val time_start = System.nanoTime()
val request = chain.request()
// 修改請(qǐng)求,添加新的請(qǐng)求頭
val newRequest = request.newBuilder()
.addHeader("User-Agent", "Mocation/1.0.0/234/iOS/18.1.1") // 添加另一個(gè)請(qǐng)求頭
.build()
val response = chain.proceed(newRequest)
val buffer = Buffer()
request.body?.writeTo(buffer)
val requestBodyStr = buffer.readUtf8()
Log.e(
"okhttp",
String.format(
"發(fā)送請(qǐng)求:%s 參數(shù):%s",
request.url,
requestBodyStr
)
)
val responseStr = response.body?.string() ?: "空返回" //response.body?.string() 在請(qǐng)求中只能調(diào)用一次,所以再返回的時(shí)候要新建一個(gè)response來(lái)返回
val mediaType = response.body?.contentType()
val newBody = ResponseBody.create(mediaType, responseStr)
val newResponse = response.newBuilder().body(newBody).build()
val time_end = System.nanoTime()
Log.e(
"okhttp",
String.format("拿到返回:%s 時(shí)間:%.1fms", request.url, (time_end - time_start) / 1e6)
)
return newResponse
}
}
這樣自定義后狞山,在OkHttpClient的Builder()后面再追加上.addInterceptor(LoggingInterceptor())
全闷,便會(huì)執(zhí)行到我們自定義的攔截器方法里。
2. gson
Gson
是由 Google 開發(fā)的一個(gè)用于 Java 和 Kotlin 的 JSON 數(shù)據(jù)解析庫(kù)萍启,用于在對(duì)象和 JSON 字符串之間進(jìn)行序列化和反序列化总珠。它功能強(qiáng)大且易于使用,在 Android 開發(fā)中非常常見(jiàn)勘纯。開發(fā)中會(huì)經(jīng)常使用Json和自定義對(duì)象的互相轉(zhuǎn)換局服,首先要在工程中添加對(duì)gson的依賴:
implementation(libs.gson)
使用的基本方法如下:
fun main() {
val gson = Gson()
val userStr = "{\"uid\":123,\"nickName\":\"甲方\"}"
val user = gson.fromJson<User>(userStr,User::class.java)
println("用戶昵稱:${user.nickName}")
println("用戶信息:${user.toString()}")
val userString = gson.toJson(user)
println("用戶字符串:${userString}")
val userArrStr = "[{\"uid\":123,\"nickName\":\"甲方\"},{\"uid\":234,\"nickName\":\"乙方\"}]"
val userList:List<User> = gson.fromJson(userArrStr, object :TypeToken<List<User>>(){}.type)
println("用戶數(shù)組:${userList}")
val userListString = gson.toJson(userList)
println("用戶數(shù)組字符串:${userListString}")
}
class User {
var uid:Int = 0
var nickName = ""
override fun toString(): String {
return "User(uid=$uid, nickName='$nickName')"
}
}
這里可以有一個(gè)方便的Android Studio插件,JsonToKotlinClass可以方便的將json字符串轉(zhuǎn)換為Kotlin中的對(duì)象驳遵。
3. Retrofit
Retrofit
是由 Square 公司開發(fā)的一個(gè)功能強(qiáng)大的 網(wǎng)絡(luò)請(qǐng)求庫(kù)淫奔,用于在 Android 開發(fā)中進(jìn)行 HTTP 網(wǎng)絡(luò)通信。它提供了簡(jiǎn)單且可擴(kuò)展的 API超埋,極大地簡(jiǎn)化了網(wǎng)絡(luò)請(qǐng)求的編寫,使得代碼更加簡(jiǎn)潔佳鳖、可維護(hù)霍殴。
簡(jiǎn)單的實(shí)現(xiàn)一個(gè)get請(qǐng)求:
object BoxRetrofit {
private const val BASEURL = "https://api.mocation.cc/api/"
val apiService: ApiService by lazy {
Retrofit.Builder()
.baseUrl(BASEURL) // 基礎(chǔ) URL
.addConverterFactory(GsonConverterFactory.create()) // Gson 轉(zhuǎn)換器
.build()
.create(ApiService::class.java)
}
}
interface ApiService {
@GET(value = "coopen/data")
fun queryNumberInfo():Call<IndexResponse>
}
data class IndexResponse(
val code: Int,
val data: CountInfo,
val msg: Any
)
data class CountInfo(
val movieCount: Int,
val placeCount: Int
)
在Retrofit.Builder()
后面也可以跟上自己的client設(shè)置自定義的OkHttpClient
,這樣就可以添加自己的攔截器進(jìn)行各種操作。
在Activity中就可以這么請(qǐng)求數(shù)據(jù):
BoxRetrofit.apiService.queryNumberInfo().enqueue(object :retrofit2.Callback<IndexResponse> {
override fun onResponse(call: Call<IndexResponse>, response: Response<IndexResponse>) {
Log.e("retrofit", "收到了 異步 返回值:${response.body()?.data?.movieCount}")
}
override fun onFailure(call: Call<IndexResponse>, t: Throwable) {
Log.e("retrofit", "收到了 異步 錯(cuò)誤返回值:${t.message}")
}
})