Android 使用HttpURLConnection

修改activity_main.xml 中的代码,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<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>

修改MainActivity 中的代码,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        sendRequestBtn.setOnClickListener {
            sendRequestWithHttpURLConnection()
        }
    }
 
    private fun sendRequestWithHttpURLConnection() {
        // 开启线程发起网络请求
        thread {
            var connection: HttpURLConnection? = null
            try {
                val response = StringBuilder()
                // 获取HttpURLConnection 的实例,一般只需创建一个URL对象,
                // 并传入目标的网络地址,然后调用一下openConnection()方法即可
                val url = URL("https://www.baidu.com")
                connection = url.openConnection() as HttpURLConnection
                // 设置连接超时、读取超时的毫秒数
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                // 调用getInputStream()方法就可以获取到服务器返回的输入流了
                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 {
                // 调用disconnect()方法将这个HTTP连接关闭
                connection?.disconnect()
            }
        }
    }
 
    private fun showResponse(response: String) {
        // Android 是不允许在子线程中进行UI操作的,
        // 而runOnUiThread()方法其实就是对异步消息处理机制进行了一层封装
        runOnUiThread {
            // 在这里进行UI操作,将结果显示到界面上
            responseText.text = response
        }
    }
}

  

posted @   草木物语  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2022-01-19 欧几里得算法(又称辗转相除法)
2022-01-19 数字证书
2022-01-19 数字签名
2022-01-19 消息认证码
2022-01-19 迪菲-赫尔曼密钥交换
2022-01-19 混合加密
2022-01-19 公开密钥加密
点击右上角即可分享
微信分享提示