Android-网络请求

1. OkHttp

OkHttp是由 Square 公司开发的一个 HTTP 客户端库,用于在 Java 和 Android 中执行网络请求。它功能强大、性能高效,并且支持各种高级特性,如连接池、请求缓存、拦截器等。采用OkHttp进行简单的getpost请求示例:

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", "收到了 异步 错误返回值:${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","当前线程2:${Thread.currentThread()}")
        val body: FormBody = FormBody.Builder()
            .build()

        val httpUrl = "${BASEURL}/article/23/like"
        Log.e("okhttp", "请求的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","当前线程3:${Thread.currentThread()}")
                Log.e("okhttp", "收到了 POST 异步 错误返回值:${e.message}")
            }
            override fun onResponse(call: Call, response: Response) {
                Log.e("okhttp","当前线程3:${Thread.currentThread()}")
                Log.e("okhttp", "收到了 POST 异步 返回值:${response.body?.string()}")
            }
        })
    }
}

在OkHttp中提供了强大的拦截器Interceptor,我们可以在自定义的Interceptor中,对请求进行修改或者对返回体进行统一的一些处理,比如要在请求头中添加通用的请求头或者在返回体中进行特殊错误的判断等

class LoggingInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val time_start = System.nanoTime()
        val request = chain.request()

        // 修改请求,添加新的请求头
        val newRequest = request.newBuilder()
            .addHeader("User-Agent", "Mocation/1.0.0/234/iOS/18.1.1")               // 添加另一个请求头
            .build()

        val response = chain.proceed(newRequest)

        val buffer = Buffer()
        request.body?.writeTo(buffer)
        val requestBodyStr = buffer.readUtf8()
        Log.e(
            "okhttp",
            String.format(
                "发送请求:%s 参数:%s",
                request.url,
                requestBodyStr
            )
        )

        val responseStr = response.body?.string() ?: "空返回" //response.body?.string() 在请求中只能调用一次,所以再返回的时候要新建一个response来返回

        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  时间:%.1fms", request.url, (time_end - time_start) / 1e6)
        )

        return newResponse
    }

}

这样自定义后,在OkHttpClient的Builder()后面再追加上.addInterceptor(LoggingInterceptor()),便会执行到我们自定义的拦截器方法里。

2. gson

Gson是由 Google 开发的一个用于 Java 和 Kotlin 的 JSON 数据解析库,用于在对象和 JSON 字符串之间进行序列化和反序列化。它功能强大且易于使用,在 Android 开发中非常常见。开发中会经常使用Json和自定义对象的互相转换,首先要在工程中添加对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("用户数组:${userList}")
    val userListString = gson.toJson(userList)
    println("用户数组字符串:${userListString}")

}

class User {
    var uid:Int = 0
    var nickName = ""
    override fun toString(): String {
        return "User(uid=$uid, nickName='$nickName')"
    }
}

这里可以有一个方便的Android Studio插件,JsonToKotlinClass可以方便的将json字符串转换为Kotlin中的对象。

3. Retrofit

Retrofit是由 Square 公司开发的一个功能强大的 网络请求库,用于在 Android 开发中进行 HTTP 网络通信。它提供了简单且可扩展的 API,极大地简化了网络请求的编写,使得代码更加简洁、可维护。
简单的实现一个get请求:

object BoxRetrofit {
    private const val BASEURL = "https://api.mocation.cc/api/"
    val apiService: ApiService by lazy {
        Retrofit.Builder()
            .baseUrl(BASEURL) // 基础 URL
            .addConverterFactory(GsonConverterFactory.create()) // Gson 转换器
            .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设置自定义的OkHttpClient,这样就可以添加自己的拦截器进行各种操作。
在Activity中就可以这么请求数据:

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", "收到了 异步 错误返回值:${t.message}")
     }
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容