调整接收协议(使用https协议的可忽略)
因为我是用apache简单建了一个web服务器,只支持http协议,所以要进行如下操作,以确保能够接收到数据。
- 在res的xml文件夹下新建了一个配置文件 network_config.xml
<?xml version="1.0" encoding="utf-8" ?> <network-security-config> <base-config cleartextTrafficPermitted="true"> <trust-anchors> <certificates src="system"/> </trust-anchors> </base-config> </network-security-config>
- 在AndroidManifest.xml配置文件中做如下修改(加粗)
<application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.OkHttp" android:networkSecurityConfig="@xml/network_config" tools:targetApi="31">
编写布局文件
这里仅定义了一个按键和一个textview。
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="open" app:layout_constraintTop_toTopOf="parent" app:layout_constraintLeft_toLeftOf="parent"/> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" " app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
访问网络
这里我选择使用OkHttp来访问网络,写了个方法,当按键点击的时候调用这个方法就行了。
fun HttpRquest() {
thread {
try {
val okhttpclient = OkHttpClient()
val request = okhttp3.Request.Builder()
.url("http://43.137.44.141/get_data.xml")
.build()
val initcontent = okhttpclient.newCall(request).execute()
val content = initcontent.body?.string()
if (content != null) {
//调用解析方法,下文中写了。
parseXML(content)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
解析数据
数据格式展示:
//要解析的数据格式
<apps>
<app>
<id>1</id>
<name>Google Maps</name>
<version>1.0</version>
</app>
<app>
<id>2</id>
<name>Chome</name>
<version>2.1</version>
</app>
<app>
<id>3</id>
<name>Google Play</name>
<version>2.3</version>
</app>
</apps>
定义了一个解析数据的方法,把解析好的数据填到textview里面去。
fun parseXML(Data: String) {
runOnUiThread {
val content=StringBuilder()
try {
val factory = XmlPullParserFactory.newInstance()
val pullParser = factory.newPullParser()
pullParser.setInput(StringReader(Data))
var eventType = pullParser.eventType
var id = ""
var name = ""
var version = ""
while (eventType != XmlPullParser.END_DOCUMENT){
val node=pullParser.name
when(eventType){
XmlPullParser.START_TAG->{
when(node){
"id"->id=pullParser.nextText()
"name"->name=pullParser.nextText()
"version"->version=pullParser.nextText()
}
}
XmlPullParser.END_TAG->{
if ("app"==node){
content.append("id:$id\tname:$name\tversion:$version\n")
Log.d("information","id:$id\tname:$name\tversion:$version")
}
}
}
eventType=pullParser.next()
}
binding.tv.text=content.toString()
}catch (e:Exception){
e.printStackTrace()
}
}
}
附上总代码,方便复制
package com.example.okhttp
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.example.okhttp.databinding.ActivityMainBinding
import okhttp3.OkHttpClient
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.StringReader
import kotlin.concurrent.thread
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.button.setOnClickListener {
HttpRquest()
}
}
fun HttpRquest() {
thread {
try {
val okhttpclient = OkHttpClient()
val request = okhttp3.Request.Builder()
.url("http://43.137.44.141/get_data.xml")
.build()
val initcontent = okhttpclient.newCall(request).execute()
val content = initcontent.body?.string()
if (content != null) {
parseXML(content)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun parseXML(Data: String) {
runOnUiThread {
val content=StringBuilder()
try {
val factory = XmlPullParserFactory.newInstance()
val pullParser = factory.newPullParser()
pullParser.setInput(StringReader(Data))
var eventType = pullParser.eventType
var id = ""
var name = ""
var version = ""
while (eventType != XmlPullParser.END_DOCUMENT){
val node=pullParser.name
when(eventType){
XmlPullParser.START_TAG->{
when(node){
"id"->id=pullParser.nextText()
"name"->name=pullParser.nextText()
"version"->version=pullParser.nextText()
}
}
XmlPullParser.END_TAG->{
if ("app"==node){
content.append("id:$id\tname:$name\tversion:$version\n")
Log.d("information","id:$id\tname:$name\tversion:$version")
}
}
}
eventType=pullParser.next()
}
binding.tv.text=content.toString()
}catch (e:Exception){
e.printStackTrace()
}
}
}
}
附上效果图