使用网络首先要申请权限,所以在配置文件中写入:
布局文件:
button按键用于触发该事件,scrollview控件可以使内容滚动显示控件,里面一般嵌套一个子布局,我这里没有嵌套,直接使用textview来显示网页输入的内容。
<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>
线程处理耗时操作,在线程中开启网络请求。
在showResponse()中开启UI线程是因为在线程中运行时不允许进行UI操作。
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.btn.setOnClickListener {
sendRequestWithHttpURLConnection()
}
}
private fun sendRequestWithHttpURLConnection() {
// 开启线程来发起网络请求
thread {
var connection: HttpURLConnection? = null
try {
val response = StringBuilder()
//需要访问的页面地址
val url = URL("https://www.baidu.com")
//创建一个HttpURLConnection实例
connection = url.openConnection() as HttpURLConnection
//设置链接超时时间
connection.connectTimeout = 8000
//设置读取超时时间
connection.readTimeout = 8000
//获取输入流
val input = connection.inputStream
// 下面对获取到的输入流进行读取
val reader = BufferedReader(InputStreamReader(input))
reader.use {
reader.forEachLine {
response.append(it)
}
}
showResponse(response.toString())
} catch (e: Exception) {
e.printStackTrace()
} finally {
//关闭HTTP链接
connection?.disconnect()
}
}
}
private fun showResponse(response: String) {
runOnUiThread {
// 在这里进行UI操作,将结果显示到界面上
binding.textView.text = response
}
}