HttpURLConnection

109 阅读1分钟
package com.example.myapplication

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            button.setOnClickListener {
            sendRequestWithHttpURLConnection()
        }
        }

    private fun sendRequestWithHttpURLConnection() {
        thread {
            var connection: HttpURLConnection? = null
            try {
                val response = StringBuilder() //创建HttpURLConnection连接对象,并设置连接参数
                val url = URL("https://www.baidu.com")
                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)
                    }
                }
                runOnUiThread { //在这里进行UI操作,将结果显示到界面上,需要切换到主线程
                    responseText.text = response
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                connection?.disconnect() //关闭连接
            }
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<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/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="sent"/>
  <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>