解析XML格式
思路
使用OkHttp的思路
- 创建OkHttpClient
- `发送http请求,创建Request对象,build()方法之前可以连缀很多其他 的方法,另外url()方法设置目标的网络地址
- 调用OkHttpClient的newcall()创建call对象,并利用execute发送这条http请求并获的服务器返回的数据
- 使用Response对象的body()方法转成String型,用来以后分析
OkHttpClient client=new OkHttpClient(); Request request=new Request.Builder().url("http://192.168.31.228/get_data.xml").build(); Response response=client.newCall(request).execute(); String responseData=response.body().string();
分析获得xml格式的数据(Pull方式)
- 获取XmlPullParserFactory实例
- 借助上面的实例获取XmlPullParser对象
- 调用XmlPullParser的setInput()方法将从服务器中获取的数据设置进去就可以解析了
- 具体的解析要用到函数
4.1 int eventType=xmlPullParser.getEventType();
4.2 String nodeName=xmlPullParser.getName()
4.3xmlPullParser.nextText();
4.4eventType=xmlPullParser.next();
4.5xmlPullParser.END_DOCUMENT 和XmlPullParser.START_TAG和 XmlPullParser.END_TAG:
遇到的问题
###** OkHttpClient 的配置问题
解决方法:在: app/build.gradledependencies闭包中添加
implementation ‘com.squareup.okhttp3:okhttp:3.7.0’
添加上述依赖,会自动下载两个库,OKHttp库和Okio库
Request 中的url访问的服务器设置
解决方法:设置成本地的ip地址,不要设置成本地局域网的地址(虽然树上是这么要求的)
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url(“http://192.168.31.228/get_data.xml”).build();
Response response=client.newCall(request).execute();
String responseData=response.body().string();
这样就可以访问本地服务器中的文件
权限设置
OKhttp使用中出现java.net.SocketException: socket failed: EACCES (Permission denied)
使用okhttp需要网络权限,所以需要在manifest中加入网络权限
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xmlanalyse">
<uses-permission android:name="android.permission.INTERNET"/><!加在这个位置>
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
新的明文机制
W/System.err: java.net.UnknownServiceException: CLEARTEXT communication to 10.240.35.113 not permitt
解决方法:
如果一定要使用明文通信的话,则可以打开AndroidManifest.xml 文件,在 application 元素中添加:
<application
android:usesCleartextTraffic="true" <!添加到这个位置>
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>