class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun myclick(view: View) {
when (view.id) {
//不能在主线程中进行get请求
R.id.get -> object : Thread() {
override fun run() {
super.run()
get()
}
}.start()
}
}
fun get() {
try {
//HttpURLConnection
//1.实例化一个URL对象
val url = URL("http://www.imooc.com/api/teacher?type=3&cid=1&type=3")
//2.获取HttpURLConnection实例
val conn = url.openConnection() as HttpURLConnection
//3.设置和请求相关的属性
//请求方式
conn.requestMethod = "GET"
//请求超时时长
conn.connectTimeout = 6000
//4.获取响应码
if (conn.responseCode == HttpURLConnection.HTTP_OK) {
//5.判断响应码并获取响应数据
//获取响应的流
val inputStream = conn.inputStream
val b = ByteArray(1024)
var len = 0
val baos = ByteArrayOutputStream()
//在循环中读取输入的流
//in.read(b); //该方法返回值是int类型数据,代表的是实际读到的数据长度
while (inputStream.read(b).also {
len = it } > -1) {
//将字节数组里面的内容存/写入缓存流
//参数1:待写入的数组
//参数2:起点
//参数3:长度
baos.write(b, 0, len)
}
val s = String(baos.toByteArray())
Log.e("TAG", "$s====")
}
} catch (e: MalformedURLException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
[Android development] GET request
Guess you like
Origin blog.csdn.net/weixin_42020386/article/details/113092028
Recommended
Ranking