首页 > 其他分享 >Android 使用HttpURLConnection

Android 使用HttpURLConnection

时间:2023-01-19 12:03:01浏览次数:40  
标签:val reader connection 使用 Android response 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
        }
    }
}

  

标签:val,reader,connection,使用,Android,response,HttpURLConnection
From: https://www.cnblogs.com/ooo0/p/17061257.html

相关文章

  • 使用Consul作为Istio的注册中心
    默认istio使用k8s作为注册中心,k8s的service、endpoint对应于服务、实例。针对一些还未接入到服务网格的SpringCloud服务,其使用的注册中心可能是consul,如何让服务网格上的......
  • Android WebView的用法
    WebView控件,借助它我们就可以在自己的应用程序里嵌入一个浏览器,从而非常轻松地展示各种各样的网页。修改activity_main.xml中的代码,如下所示:<LinearLayoutxmlns:andr......
  • 浅谈使用实现FactoryBean接口的方式定义Bean
    在定义一个Bean的时候,我们可以直接实现FactoryBean接口,然后重写对应的getXxx方法,就能够完成一个Bean的定义工作文章目录​​一、使用实现接口的方式定义Bean​​​​二、其......
  • MetadataReader、ClassMetadata、AnnotationMetadata的简单使用
    在Spring源码中有很多场景会去解析类的信息,比如类名、类中的方法、类上的注解,这些都可以称之为类的元数据,在Spring中对类的元数据做了抽象,并提供了一些工具类。MetadataRead......
  • MyBatis使用foreach批量插入一个含List<实体>成员变量的实体类
    文章目录​​一、List<String>​​​​二、List<IntEntity>​​​​三、再次修改​​MyBatis使用foreach批量插入一个实体类数据,其中这个实体类包含一个List的成员变量。即......
  • AIRIOT答疑第6期|如何使用二次开发引擎?
    ​​灵活扩展,满足客户定制化需求 AIRIOT物联网低代码平台提供丰富的前端、后台服务二次开发接口,具备灵活的组件服务部署与管理能力,对任何功能模块进行二次开发,满足客......
  • anaconda使用
    查看所有环境condainfo--envs或者condaenvlist创建环境condacreate --nameenvnamepython=3.7激活环境condaactivateenvname安装pytorchcondains......
  • 使用Sharding-JDBC 实现Mysql读写分离
    为什么要读写分离?读写分离则是将事务性的增、改、删操作在主库执行,查询操作在从库执行。一般业务的写操作都是比较耗时,为了避免写操作影响查询的效率,可以使用读写分离。当然......
  • 使用Gradle构建Java项目
    引入springboot插件该插件发布在Gradle的插件门户网站上,可以使用插件块来应用:plugins{id'org.springframework.boot'version'2.3.7.RELEASE'//维护springboot......
  • Android 使用通知
    通知(notification)是Android系统中比较有特色的一个功能,当某个应用程序希望向用户发出一些提示信息,而该应用程序又不在前台运行时,就可以借助通知来实现。发出一条通知后,手......