目录
一、为什么要使用OkHhttp?
在不使用OkHhttp之前,我们都是在使用什么?使用HttpURLConnection,那么我们看看HttpURLConnection发起一次请求,两次请求要花多长时间,而OkHttp花多长时间。HttpURLConnection会比okhttp花更多的时间。
(1)HttpURLConnection
fun sendGetRequest(urlString: String): String? {
var response: String? = null
var startTime = System.currentTimeMillis() // 记录开始时间
try {
val url = URL(urlString)
val connection = url.openConnection() as HttpURLConnection
// 设置请求方法为GET
connection.requestMethod = "GET"
// 连接服务器
val responseCode = connection.responseCode
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应内容
val inputStream = connection.inputStream
val reader = BufferedReader(InputStreamReader(inputStream))
val responseBuilder = StringBuilder()
val readLine = reader.readLine()
println("GET请求成功:$readLine")
response = responseBuilder.toString()
}<