导入相关依赖
//okhttp3依赖
compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.9.0'
//Gson(谷歌官方 Json 库)
implementation 'com.google.code.gson:gson:2.8.5'
所用插件:JSON TO Kotlin Class(不会安装自己百度去)
代码块
数据类:(这里是根据插件生成的类体)
data class Emp(
val `data`: List<Data>,
val message: String,
val status: Int
)
data class Data(
val id: Int,
val nextUserPlStepId: Int,
val userProductionLineId: Int,
val userWorkId: Int
)
Main类
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
class MainActivity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
val runnable = Runnable {
val initData = initData("http://xxx.xxx.xxx.xxx:8080/dataInterface/UserPlStep/search");
val emp = Gson().fromJson(initData, Emp::class.java)
runOnUiThread {
emp.data.forEach { println("id:${it.id} nextId:${it.nextUserPlStepId}") }
}
}
Thread(runnable).start()
}
//网络请求封装(这里不讲安全!简单陈述实现步骤)
private fun initData(url : String): String? {
val build = Request.Builder().url(url).build()
val execute = OkHttpClient().newCall(build).execute();
return execute.body?.string()
}
}
ok!