Android学习-网络请求(OKHTTP)

272 阅读1分钟

引入库

implementation(platform("com.squareup.okhttp3:okhttp-bom:4.10.0"))
// define any required OkHttp artifacts without version
implementation("com.squareup.okhttp3:okhttp")
implementation("com.squareup.okhttp3:logging-interceptor")

简单的 Basic 认证接口请求

fun networking(){
    //S3
    Log.i("Authorization", auth)
    val okHttpClient: OkHttpClient = OkHttpClient()

    val request: Request = Request.Builder()
        .url("https://copd-indicator-dev.osapling.com/uniform-api/IndicatorJob/100")
        .addHeader("Charset", "UTF-8")
        .addHeader("Content-Type", "application/json; charset=UTF-8")
        .addHeader("Authorization", "Basic $auth")
        .build()

    okHttpClient.newCall(request).enqueue(object :Callback{
        override fun onFailure(call: Call, e: IOException) {

            Log.i("onFailure", e.toString())
        }
        override fun onResponse(call: Call, response: Response) {

            Log.i("onResponse", "${response}")
        }
    })

}