MainActivity.kt
package com.example.fredric.sendrequestwithokhttp
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import okhttp3.OkHttpClient
import okhttp3.Request
import org.xml.sax.InputSource
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.StringReader
import javax.xml.parsers.SAXParserFactory
class MainActivity : AppCompatActivity(), View.OnClickListener{
var responseText: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var sendRequest = findViewById<Button>(R.id.send_request)
responseText = findViewById<TextView>(R.id.response_text)
sendRequest.setOnClickListener(this)
}
override fun onClick(v: View?) {
if(v?.id == R.id.send_request) {
sendRequestWithOkHttp()
}
}
fun showResponse(responseData: String?) {
runOnUiThread(object: Runnable{
override fun run() {
responseText?.setText(responseData)
}
})
}
fun parseXMLWithPull(responseData:String) {
try {
var factory = XmlPullParserFactory.newInstance()
var pullParser = factory.newPullParser()
pullParser.setInput(StringReader(responseData))
var eventType = pullParser.eventType
var id = ""
var name = ""
var version = ""
while (eventType != XmlPullParser.END_DOCUMENT) {
var nodeName = pullParser.name
when(eventType) {
XmlPullParser.START_TAG -> {
if("id".equals(nodeName)) {
id = pullParser.nextText()
}else if("name".equals(nodeName)) {
name = pullParser.nextText()
}else if("version".equals(nodeName)) {
version = pullParser.nextText()
}
}
XmlPullParser.END_TAG -> {
if("app".equals(nodeName)) {
Log.d("MainActivity","id is: "+id)
Log.d("MainActivity","name is: "+name)
Log.d("MainActivity","version is: "+version)
}
}
else -> {
}
}
eventType = pullParser.next()
}
}catch (ex: Exception) {
ex.printStackTrace()
}
}
fun parseXMLWithSax(xmlData: String) {
try {
var factory = SAXParserFactory.newInstance()
var xmlReader = factory.newSAXParser().xmlReader
var handler = ContentHandler()
xmlReader.contentHandler = handler
xmlReader.parse(InputSource(StringReader(xmlData)))
}catch (ex: Exception) {
ex.printStackTrace()
}
}
fun sendRequestWithOkHttp() {
Thread(object: Runnable{
override fun run() {
try {
var client = OkHttpClient()
var request = Request.Builder().
url("http://192.168.0.102/get_data.xml").
build()
var response = client.newCall(request).execute()
var responseData = response.body().string()
showResponse(responseData)
// parseXMLWithPull(responseData)
parseXMLWithSax(responseData)
}catch (ex: Exception) {
ex.printStackTrace()
}
}
}).start()
}
}
ContentHander.kt
package com.example.fredric.sendrequestwithokhttp
import android.util.Log
import org.xml.sax.Attributes
import org.xml.sax.SAXException
import org.xml.sax.helpers.DefaultHandler
class ContentHandler : DefaultHandler() {
var nodeName: String? = null
var id: StringBuilder? = null
var name: StringBuilder? = null
var version: StringBuilder? = null
@Throws(SAXException::class)
override fun startDocument() {
id = StringBuilder()
name = StringBuilder()
version = StringBuilder()
}
@Throws(SAXException::class)
override fun endDocument() {
super.endDocument()
}
@Throws(SAXException::class)
override fun startElement(uri: String, localName: String, qName: String, attributes: Attributes) {
nodeName = localName
}
@Throws(SAXException::class)
override fun characters(ch: CharArray, start: Int, length: Int) {
if("id".equals(nodeName)) {
id?.append(ch,start,length)
}else if("name".equals(nodeName)) {
name?.append(ch,start,length)
}else if("version".equals(nodeName)) {
version?.append(ch, start, length)
}
}
@Throws(SAXException::class)
override fun endElement(uri: String, localName: String, qName: String) {
if("app".equals(localName)) {
Log.d("ContentHandler","id is :" + id?.toString()?.trim())
Log.d("ContentHandler","name is :" + name?.toString()?.trim())
Log.d("ContentHandler","version is :" + version?.toString()?.trim())
id?.setLength(0)
name?.setLength(0)
version?.setLength(0)
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/send_request"
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/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fredric.sendrequestwithokhttp">
<uses-permission android:name="android.permission.INTERNET" />
<application
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>
运行效果,