Android 使用HttpURLConnection
修改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>
修改MainActivity 中的代码,如下所示:
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
}
}
}

浙公网安备 33010602011771号