okhttp应用实例
时间: 2023-08-28 12:18:23 浏览: 123
Okhttp示例
OkHttp是一个开源的HTTP客户端库,用于在Android应用程序中进行网络请求。下面是一个使用OkHttp的应用实例:
```kotlin
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
class OkHttpManager(private val activity: Activity) {
fun get(url: String) {
val client = OkHttpClient()
val request = Request.Builder().get().url(url).build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
ToastUtil.showToast(activity, "Get 失败")
}
override fun onResponse(call: Call, response: Response) {
val responseStr = response.body()?.string()
activity.runOnUiThread {
ToastUtil.showToast(activity, responseStr)
}
}
})
}
}
```
以上代码示例了如何使用OkHttp发送一个GET请求,并在响应返回后处理结果。其中,`OkHttpManager`是一个封装了OkHttp操作的类,`get`方法接收一个URL参数,创建一个GET请求,并异步执行。在响应返回时,通过回调方法处理成功或失败的情况,并在UI线程上显示响应结果。
请注意,这只是一个简单的示例,实际应用中可能还需要处理更多的错误和异常情况,以及其他类型的请求和响应。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [OkHttp日常使用实战篇](https://blog.csdn.net/sinat_35241409/article/details/118912417)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *2* [OkHttp使用实例](https://blog.csdn.net/eieiei438/article/details/80062984)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文