学习之鸿蒙&Android

Android中的网络访问

2021-07-15  本文已影响0人  别看后面有人

http请求的工作原理:客户端向服务器发出一条http请求,服务器收到之后会返回一些数据给客户端,然后客户端对这些数据进行解析和处理,android中提供了Webview控件,因为后台以及帮我们处理好发送http请求、接收服务器响应、解析返回数据,以及最后页面显示,只不过它封装的太好了,使我们不能直观的看出http是如何工作的
1.使用HttpURLConnection
android中发送http有两种方式,HttpUrlConnection和HttpClient,在6.0系统中HttpClient被完全废弃。HttpURLConnection的使用:首先获取HttpURLConnection的实例,一般是创建一个URL对象,并且传入目标网络地址,然后调用openConnection()方法

  fun getHttpUrlConnection(){
        var result=""
        val  url=URL("https://www.baidu.com")
        val httpUrlConnectin=url.openConnection() as HttpURLConnection
        try {
            httpUrlConnectin.requestMethod="get"
            httpUrlConnectin.connectTimeout=8000
            httpUrlConnectin.readTimeout=8000

            val response=StringBuilder()
            val input=httpUrlConnectin.inputStream
            val reader=BufferedReader(InputStreamReader(input))
            reader.use {
                reader.forEachLine {
                    response.append(it)
                }
            }
            result=response.toString()
        }catch (e:Exception){
            e.printStackTrace()
        }finally {
            httpUrlConnectin.disconnect() 
        }       
    }

这里网络请求用了一个子线程,然后在子线程HttpURLConnection发出一条HTTP请求,我们指定Android中是不允许子线程操作UI的,所以使用该方法的时候要调用runOnUiThread()方法进行

2.使用okHttp
okHttp使用的时候先安装okhttp的依赖,添加依赖一般会自动下载俩个:一个是okhttp,一个是okio库,后者是前者通信的基础

 fun getOkHttpResponse(){
        var result=""
        thread {
            try {
                val client=OkHttpClient()
                val request=Request.Builder()
                    .url("https://www.baidu.com")
                    .build()

                val response=client.newCall(request) .execute()
                val responseData=response.body?.string()

                if (responseData!=null){
                    result=responseData
                } 
            }catch (e:Exception){
              e.printStackTrace()  
            }
            
            
        }
    }

3.最好用的Retrofit
服务器接口地址静止不变的时候

GET http://demo.com/get_data.json

interface DemoService{
 @GET("get_data.json")
 fun getData(): Call<Data>
}

接口地址部分内容变化的情况

GET http://demo.com/<page>/get_data.json

interface DemoService{
 @GET("{page}/get_data.json")
 fun getData(@Path("page") page:Int): Call<Data>
}

@GET当中指定的接口地址当中,这里使用了一个{page}占位符,然后又在getData()方法发起请求时,Retrofit会自动将page参数的值替换到占位符的位置

GET http://demo.com/get_data.json?u=<user>&t=<token>

interface DemoService{
 @GET("{page}/get_data.json")
 fun getData(@Query("u") user:String,@Query("t") token:String): Call<Data>
}

在getData()中添加了user和token这两个参数,并使用@Query注解对他们进行申明。这样当网络发起请求时,Retrofit就会自动按照带参数GET请求的格式将这俩个参数构建到请求当中。

上一篇下一篇

猜你喜欢

热点阅读