在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使用详解