在Android開發中網絡請求是最常用的操作之一, Android SDK中對HTTP(超文本傳輸協議)也提供了很好的支持,這裏包括兩種接口:
1、標準Java接口(java.NET) —-HttpURLConnection,可以實現簡單的基於URL請求、響應功能;
2、Apache接口(org.appache.http)—-HttpClient,使用起來更方面更強大。
但在android API23的SDK中Google將HttpClient移除了。Google建議使用httpURLconnection進行網絡訪問操作。
HttpURLconnection是基於http協議的,支持get,post,put,delete等各種請求方式,最常用的就是get和post
Glide裏面的網絡請求,默認用的是HttpUrlFetcher,內部是用HttpUrlConnection(Get)得到inputStream
Get請求舉個例子:
private fun httpUrlConnectionGet() {
object : Thread() {
override fun run() {
val urlStr = "https://www.baidu.com/"
val url = URL(urlStr)
//得到connection對象。
val connection = url.openConnection() as HttpURLConnection
//設置請求方式,默認就是GET,可以不指定
connection.requestMethod = "GET"
//連接
connection.connect()
//得到響應碼
val responseCode = connection.responseCode
if (responseCode == HttpURLConnection.HTTP_OK) {
//得到響應流
val inputStream = connection.inputStream
Log.d("zhen", "result======= $inputStream ======${convert2String(inputStream)}")
val inputStream2 = connection.inputStream
Log.w("zhen", "result======= $inputStream2 ======${convert2String(inputStream2)}")
}
}
}.start()
}
private fun convert2String(inputStream: InputStream): String {
val result = ByteArrayOutputStream()
val buffer = ByteArray(1024)
var length = inputStream.read(buffer)
while (length != -1) {
result.write(buffer, 0, length)
length = inputStream.read(buffer)
}
return result.toString(StandardCharsets.UTF_8.name())
}
- HttpURLconnection是同步的請求,所以必須放在子線程中
- connection.getInputStream()只是得到一個流對象,並不是數據,不過我們可以從流中讀出數據,從流中讀取數據的操作必須放在子線程
- connection.getInputStream()得到一個流對象,從這個流對象中只能讀取一次數據,第二次讀取時將會得到空數據。
參考:
HttpUrlConnection使用詳解