以下是MainActivity文件里面的部分代码:
private fun sendRequestWithHttpURLConnection() {
Log.d("MainActivity_send", "Hello World")
Thread {
//创建一个 网络请求变量
var connection: HttpURLConnection? = null
try {
//对网络网页的数据进行保存
val response = StringBuilder()
//需要访问的网址
val url = URL("https://www.baidu.com")
connection = url.openConnection() as HttpURLConnection // as强制类型转换操作符
//连接超时 时限
connection.connectTimeout = 8000
//读取超时时限
connection.readTimeout = 8000
//获取输入流的全部数据
val input = connection.inputStream
//下面对获取到的输入流进行读取
val reader = BufferedReader(InputStreamReader(input))
//use函数内部实现也是通过try-catch-finally块捕捉的方式,
reader.use {
reader.forEachLine {
//将数据追加到变量中
response.append(it)
}
}
showResponse(response.toString())
} catch (e: Exception) {
e.printStackTrace()
} finally {
connection?.disconnect()
}
}.start()
}
以下是activity_main.xml文件代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/sendRequestBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request" />
<!-- 滑轮,查看更多的数据-->
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/responseText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
下列是效果图

但是再点击Send Request 后,并没有任何反应。经过查看过后相应的Debug后,发现是由于在启动子线程的时候使用Thread语法糖,末尾没有调用start()方法。来启动Thread子线程。
将代码改为以下即可:
private fun sendRequestWithHttpURLConnection() {
Log.d("MainActivity_send", "Hello World")
Thread {
//创建一个 网络请求变量
var connection: HttpURLConnection? = null
try {
//对网络网页的数据进行保存
val response = StringBuilder()
//需要访问的网址
val url = URL("https://www.baidu.com")
connection = url.openConnection() as HttpURLConnection // as强制类型转换操作符
//连接超时 时限
connection.connectTimeout = 8000
//读取超时时限
connection.readTimeout = 8000
//获取输入流的全部数据
val input = connection.inputStream
//下面对获取到的输入流进行读取
val reader = BufferedReader(InputStreamReader(input))
//use函数内部实现也是通过try-catch-finally块捕捉的方式,
reader.use {
reader.forEachLine {
//将数据追加到变量中
response.append(it)
}
}
showResponse(response.toString())
} catch (e: Exception) {
e.printStackTrace()
} finally {
connection?.disconnect()
}
}.start()
}
这样即可通过点击实现以下效果:

备注:十分感谢,点击效果图来自:https://blog.youkuaiyun.com/qq_37080185/article/details/114709422
2629





