HttpURLConnection的使用

使用网络首先要申请权限,所以在配置文件中写入:

布局文件:

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
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值