《第一行代码 第3版》学习笔记——第十一章 网络技术

1 webview用法

class MainActivity : ComponentActivity() {
   
    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
   
        super.onCreate(savedInstanceState)
        setContent {
   
            NetWorkDemoTheme {
   
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
   
                    AndroidView(factory = {
    context ->
                        WebView(context).apply {
   
                            webViewClient = object : WebViewClient() {
   
                                override fun shouldOverrideUrlLoading(
                                    view: WebView?,
                                    request: WebResourceRequest?
                                ): Boolean {
   
                                    try {
   
                                        if (url!!.startsWith("baiduboxapp://")) {
   
                                            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                                            startActivity(intent)
                                            return true
                                        }
                                    } catch (e: Exception) {
   
                                        return false
                                    }
                                    view?.loadUrl(url!!)
                                    return true
                                }
                            }
                            settings.javaScriptEnabled = true
                            loadUrl("https://www.baidu.com/")
                        }
                    })
                }
            }
        }
    }
}

Compose没有WebView控件,使用传统的WebView控件,创建一个WebViewClient对象,用于展示百度首页。loadUrl函数加载百度首页数据。javaScriptEnabled用于加载JavaScript样式
由于baidu有自定义scheme,所以这里做了特殊处理

2 使用http访问网络

class MainActivity : ComponentActivity() {
   
    override fun onCreate(savedInstanceState: Bundle?) {
   
        super.onCreate(savedInstanceState)
        setContent {
   
            NetWorkDemoTheme {
   
                // A surface container using the 'background' color from the theme
                Surface(
                    color = MaterialTheme.colorScheme.background
                ) {
   
                    ShowHttp()
                }
            }
        }
    }
}

@Composable
fun ShowHttp() {
   
    var response by remember {
   
        mutableStateOf("")
    }
    LazyColumn {
   
        item {
   
            Button(
                onClick = {
   
                    thread {
   
                        var conn: HttpURLConnection? = null
                        try {
   
                            val res = StringBuilder()
                            val url = URL("https://www.baidu.com")
                            conn = url.openConnection() as HttpURLConnection
                            conn.connectTimeout = 8000
                            conn.readTimeout = 8000
                            val input = conn.inputStream
                            val reader = BufferedReader(InputStreamReader(input))
                            reader.use {
   
                                reader.forEachLine {
   
                                    res.append(it)
                                }
                            }
                            response = res.toString()
                            Log.i("TAG", "response = $response ")
                        } catch (e: Exception) {
   
                            e.printStackTrace()
                        } finally {
   
                            conn?.disconnect()
                        }
                    }
                },
                modifier = Modifier.fillMaxWidth()
            ) {
   
                Text(text = "request")
            }
        }
        item {
   
            Button(
                onClick = {
   
                    thread {
   
                        try {
   
                            val client = OkHttpClient()
                            val request = Request.Builder()
                                .url("https://www.baidu.com")
                                .build()
                            val res = client.newCall(request).execute()
                            val responseData = res.body?.string()
                            if (responseData != null) {
   
                                response = responseData
                            }
                        } catch (e: Exception) {
   
                            e.printStackTrace()
                        }
                    }
                },
                modifier = Modifier.fillMaxWidth()
            ) {
   
                Text(text = "request from okhttp")
            }
        }
        item {
   
            Text(text = response)
        }
    }
}

这里创建两个按钮,一个数据展示的空间。两个按钮是两种使用http访问网络的方式,第一种是Java自带的HttpURLConnection相关的API,第二种是使用okhttp这个开源框架。
下面是访问baidu之后的打印界面
在这里插入图片描述

3 解析xml数据

网络上的数据经常使用xml或json进行传输,需要学习怎么对xml和json类型数据进行解析
这个使用pull和sax方式解析xml

class MainActivity : ComponentActivity() {
   
    private final val TAG = "MainActivity"
    override fun onCreate(savedInstanceState: Bundle?) {
   
        super.onCreate(savedInstanceState)
        setContent {
   
            NetWorkDemoTheme {
   
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
   
                    XmlPage {
    sendRequestForXml() }
                }
            }
        }
    }

    private fun sendRequestForXml() {
   
        thread {
   
            try {
   
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://192.168.12.148:12345/get_data_xml")
                    .build()
                val response &#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值