Android 网络请求示例:使用 HttpURLConnection 和 OkHttp
package com.example.networktest
import android.media.tv.AdResponse import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.example.networktest.databinding.ActivityMainBinding import com.google.gson.Gson import com.google.gson.reflect.TypeToken import okhttp3.Call import okhttp3.Callback import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.json.JSONArray import org.xml.sax.InputSource import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserFactory import java.io.BufferedReader import java.io.DataOutputStream import java.io.IOException import java.io.InputStreamReader import java.io.StringReader import java.net.HttpURLConnection import java.net.URL import javax.xml.parsers.SAXParserFactory import kotlin.concurrent.thread
class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding
interface HttpCallbackListener {
fun onFinish(response: String)
fun onError(e: Exception)
}
object HttpUtil {
fun sendHttpRequest(address: String, listener: HttpCallbackListener) {//: String {
var connection: HttpURLConnection? = null
try {
val response = StringBuilder()
val url = URL(address)
connection = url.openConnection() as HttpURLConnection
connection.connectTimeout = 8000
connection.readTimeout = 8000
val input = connection.inputStream
val reader = BufferedReader(InputStreamReader(input))
reader.use {
reader.forEachLine { response.append(it) }
}
//return response.toString()
// 回调onFinish()方法
listener.onFinish(response.toString())
} catch (e: Exception) {
e.printStackTrace()
//return e.message.toString()
// 回调onError()方法
listener.onError(e)
} finally {
connection?.disconnect()
}
}
fun sendOkHttpRequest(address: String, callback: okhttp3.Callback) {
val client = OkHttpClient()
val request = Request.Builder()
.url(address)
.build()
client.newCall(request).enqueue(callback)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.sendRequestBtn.setOnClickListener { sendRequestWithHttpURLConnection() }
binding.OkHttpsendRequestBtn.setOnClickListener { sendRequestWithOkHttp() }
binding.JsonsendRequestBtn.setOnClickListener { sendRequestWithJson() }
}
private fun sendRequestWithJson() {
thread {
/*val address = 'http://192.168.0.115/get_data.json'
val responseData = HttpUtil.sendRequestWith(address)
if (responseData != null) {
showResponse(responseData)//将信息写出来
//解析xml数据
//parseXMLWithPull(responseData)//Pull解析方式
//parseXMLWithSAX(responseData)//SAX解析方式
//解析JSON数据
//parseJSONWithJSONObject(responseData)//JSONObject解析方法
parseJSONWithGSON(responseData)//GSON解析
}*/
try {
val client = OkHttpClient()
val request = Request.Builder()
//.url('https://www.baidu.com')
// 指定访问的服务器地址是计算机本机get_data.xml文件
//.url('http://192.168.0.115/get_data.xml')
//指定访问的服务器地址是计算机本机get_data.json文件
.url('http://192.168.0.116/get_data.json')
.build()
val response = client.newCall(request).execute()
val responseData = response.body?.string()
if (responseData != null) {
showResponse(responseData)//将信息写出来
//解析xml数据
//parseXMLWithPull(responseData)//Pull解析方式
//parseXMLWithSAX(responseData)//SAX解析方式
//解析JSON数据
//parseJSONWithJSONObject(responseData)//JSONObject解析方法
parseJSONWithGSON(responseData)//GSON解析
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun sendRequestWithOkHttp() {
thread {
try {
val client = OkHttpClient()
val request = Request.Builder()
//.url('https://www.baidu.com')
// 指定访问的服务器地址是计算机本机get_data.xml文件
.url('http://192.168.0.116/get_data.xml')
//指定访问的服务器地址是计算机本机get_data.json文件
//.url('http://192.168.0.115/get_data.json')
.build()
val response = client.newCall(request).execute()
val responseData = response.body?.string()
if (responseData != null) {
showResponse(responseData)//将信息写出来
//解析xml数据
parseXMLWithPull(responseData)//Pull解析方式
//parseXMLWithSAX(responseData)//SAX解析方式
//解析JSON数据
//parseJSONWithJSONObject(responseData)//JSONObject解析方法
//parseJSONWithGSON(responseData)//GSON解析
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun parseJSONWithGSON(jsonData: String) {
val gson = Gson()
//要借助TypeToken将期望解析成的数据类型传入fromJson()方法中
val typeOf = object : TypeToken<List<App>>() {}.type
val appList = gson.fromJson<List<App>>(jsonData, typeOf)
for (app in appList) {
Log.d('MainActivity', 'id is ${app.id}')
Log.d('MainActivity', 'name is ${app.name}')
Log.d('MainActivity', 'version is ${app.version}')
}
}
private fun parseJSONWithJSONObject(jsonData: String) {
try {
val jsonArray = JSONArray(jsonData)
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
//调用getString()方法将这些数据取出
val id = jsonObject.getString('id')
val name = jsonObject.getString('name')
val version = jsonObject.getString('version')
Log.d('MainActivity', 'id is $id')
Log.d('MainActivity', 'name is $name')
Log.d('MainActivity', 'version is $version')
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun parseXMLWithSAX(xmlData: String) {
try {
val factory = SAXParserFactory.newInstance()
val xmlReader = factory.newSAXParser().getXMLReader()
val handler = ContentHandler()
// 将ContentHandler的实例设置到XMLReader中
xmlReader.contentHandler = handler
// 开始执行解析
xmlReader.parse(InputSource(StringReader(xmlData)))
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun parseXMLWithPull(xmlData: String) {
try {
//XmlPullParserFactory的实例
val factory = XmlPullParserFactory.newInstance()
val xmlPullParser = factory.newPullParser()
//调用XmlPullParser的setInput()方法将服务器返回的XML数据设置进去
xmlPullParser.setInput(StringReader(xmlData))
//通过getEventType()可以得到当前的解析事件
var eventType = xmlPullParser.eventType
var id = ''
var name = ''
var version = ''
while (eventType != XmlPullParser.END_DOCUMENT) {
val nodeName = xmlPullParser.name
when (eventType) {
// 开始解析某个节点
XmlPullParser.START_TAG -> {
when (nodeName) {
'id' -> id = xmlPullParser.nextText()
'name' -> name = xmlPullParser.nextText()
'version' -> version = xmlPullParser.nextText()
}
}
// 完成解析某个节点
XmlPullParser.END_TAG -> {
if ('app' == nodeName) {
Log.d('MainActivity', 'id is $id')
Log.d('MainActivity', 'name is $name')
Log.d('MainActivity', 'version is $version')
}
}
}
eventType = xmlPullParser.next()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun sendRequestWithHttpURLConnection() {
// 开启线程发起网络请求
thread {
val address = 'https://www.baidu.com'
//val response = HttpUtil.sendHttpRequest(address)
/*HttpUtil.sendHttpRequest(address, object : HttpCallbackListener {
override fun onFinish(response: String) {
// 得到服务器返回的具体内容
showResponse(response)
}
override fun onError(e: Exception) {
// 在这里对异常情况进行处理
}
})*/
HttpUtil.sendOkHttpRequest(address, object : Callback {
override fun onResponse(call: Call, response: Response) {
// 得到服务器返回的具体内容
val responseData = response.body?.string()
}
override fun onFailure(call: Call, e: IOException) {
// 在这里对异常情况进行处理
}
})
//showResponse(response)
/*var connection:HttpURLConnection?=null
try {
val response = StringBuilder()
val url = URL('https://www.baidu.com')
connection=url.openConnection() as HttpURLConnection
connection.requestMethod = 'POST'
/*val output = DataOutputStream(connection.outputStream)
//数据与数据之间用“&”符号隔开
output.writeBytes('username=admin&password=123456')*/
connection.connectTimeout=8000
connection.readTimeout=8000
val input=connection.inputStream
// 下面对获取到的输入流进行读取
val reader=BufferedReader(InputStreamReader(input))
reader.use {
reader.forEachLine { response.append(it) }
}
showResponse(response.toString())
}catch (e:Exception){
e.printStackTrace()
}finally {
connection?.disconnect()
}*/
}
}
private fun showResponse(response: String) {
runOnUiThread {
// 在这里进行UI操作,将结果显示到界面上
binding.responseText.text = response
}
}
}
原文地址: https://www.cveoy.top/t/topic/qpGh 著作权归作者所有。请勿转载和采集!