网络
安卓主页的网络框架:OkHttp
在OkHttp的基础上进行封装的:Retrofit框架,更常使用
OkHttp学习
在使用网络请求的时候,先添加网络访问权限:
<uses-permission android:name="android.permission.INTERNET" />
类似还有其他:
<!--网络权限-->
<uses-permission android:name="android.permission.INTERNET" />
<!--写文件权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--读文件权限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
除此之外,还有添加两个依赖:
在app-build.gradle-dependencies
下:
implementation("com.squareup.okhttp3:okhttp:4.9.0")
// 网络请求日志打印
implementation("com.squareup.okhttp3:logging-interceptor:4.9.0")
在高版本下,需要满足HTTPS的要求,如果你调试使用的是HTTP的接口,要加上:
android:usesCleartextTraffic="true"
没有请求的接口?
这个网站可以模拟接口请求:点我
或者
使用 天气预报
Get请求
同步请求
private val BaseUrl = "http://www.tianqiapi.com"
val client = OkHttpClient.Builder()//build构造者设计模式
.connectTimeout(10, TimeUnit.SECONDS)//链接超时时间
.readTimeout(10, TimeUnit.SECONDS)//读取超时时间
.writeTimeout(10, TimeUnit.SECONDS)//写超时时间,也就是请求超时
.build()
//get方法
fun get(url: String){
//创建一个子线程
Thread(Runnable {
val string2 = BaseUrl + url
println("string2 = ${string2}")
val request: Request = Request.Builder()//build构造者设计模式
.url(string2)//请求地址
.build()
//client对象 与 request产生关联,返回一个Call对象
val call: Call = client.newCall(request)
//执行,返回一个Response对象(execute()是同步请求)
val response: Response = call.execute()
//获取body
val body:String? = response.body?.string()
//结果打印
Log.e("OKHTTP", "get response body = ${body}")
println("get response body = ${body}")
}).start()
}
异步请求
///异步get请求
fun getAsync(url: String){
val string2 = BaseUrl + url
println("string2 = ${string2}")
val request: Request = Request.Builder()//build构造者设计模式
.url(string2)//请求地址
.build()
//client对象 与 request产生关联,返回一个Call对象
val call: Call = client.newCall(request)
//执行,返回一个Response对象(enqueue()是异步请求)
val response: Unit = call.enqueue(object :Callback{
override fun onFailure(call: Call, e: IOException) {
Log.e("OKHTTP", "get response body = ${e.message}")
println("error = ${e.message}")
}
override fun onResponse(call: Call, response: Response) {
//获取body
val body:String? = response.body?.string()
//结果打印
Log.e("OKHTTP", "get response body = ${body}")
println("get response body = ${body}")
}
})
}
Post请求
同步请求
//post方法
fun post(url: String){
//创建一个子线程
Thread(Runnable {
//创建body
val body2 = FormBody.Builder()
.add("key", "value")//添加参数
.add("key2", "value2")
.build()
val string2 = BaseUrl + url
println("string2 = ${string2}")
val request: Request = Request.Builder()//build构造者设计模式
.url(string2)//请求地址
.post(body2)//接口参数
.build()
//client对象 与 request产生关联,返回一个Call对象
val call: Call = client.newCall(request)
//执行,返回一个Response对象(execute()是同步请求)
val response: Response = call.execute()
//获取body
val body:String? = response.body?.string()
//结果打印
Log.e("OKHTTP", "get response body = ${body}")
println("get response body = ${body}")
}).start()
}
异步请求
//post异步方法
fun postAsync(url: String){
//创建body
val body2 = FormBody.Builder()
.add("key", "value")//添加参数
.add("key2", "value2")
.build()
val string2 = BaseUrl + url
println("string2 = ${string2}")
val request: Request = Request.Builder()//build构造者设计模式
.url(string2)//请求地址
.post(body2)//接口参数
.build()
//client对象 与 request产生关联,返回一个Call对象
val call: Call = client.newCall(request)
//执行,返回一个Response对象(enqueue()是同步请求)
val response: Unit = call.enqueue(object :Callback{
override fun onFailure(call: Call, e: IOException) {
TODO("Not yet implemented")
}
override fun onResponse(call: Call, response: Response) {
//获取body
val body:String? = response.body?.string()
//结果打印
Log.e("OKHTTP", "get response body = ${body}")
println("get response body = ${body}")
}
})
}
拦截器
LoggingInterceptor
//继承Interceptor
class LoggingInterceptor : Interceptor{
//重写方法
override fun intercept(chain: Interceptor.Chain): Response {
//获取当前请求的时间戳
val time_start = System.nanoTime()
//获取请求对象
var request = chain.request()
//获取响应对象
var response = chain.proceed(request)
//获取body
var buffer = okio.Buffer()
request.body?.writeTo(buffer)
var requestBodyString = buffer.readUtf8()
//打印
Log.e("OKHTTP", String.format("request: %s, params: %s", request.url, requestBodyString))
val businessData: String = response.body?.string() ?: "空"
Log.e("OKHTTP", businessData);
//此处需要创建新的response并返回,非直接返回
return response
}
}
GSON解析
首先,添加依赖:
implementation 'com.google.code.gson:gson:2.8.6'
JSON转model
import com.google.gson.Gson
fun main(){
//json串
val json ="{\"uid\":\"00001\",\"userName\":\"Freeman\",\"telNumber\":\"13000000000\"}";
//创建一个gson对象
var gson = Gson()
//json转model
val account = gson.fromJson<Account>(json, Account::class.java);
//打印某一个账号的名字
println(account.userName)
//打印所有属性
println(account.toString())
}
class Account{
var uid: String = "001"
var userName: String = "jack"
var password: String = "123456"
var telNumber: String = "130000000"
override fun toString(): String {
return "Account(uid='$uid', userName='$userName', password='$password', telNumber='$telNumber')"
}
}
model转JSON
//model转Json
println("model转Json ${gson.toJson(account)}")
JsonToKotlin
插件:可以将json转化为模型定义属性
Fragment
fragment不能单独使用,要嵌在activity里面
fragment的生命周期,受宿主(activity)的生命周期的影响
fragment的生命周期:
//Activity
class FragmentStudyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fragment_study)
//创建fragment对象
val fragment = FragmentStudy()
//传递数据
//创建一个bundle
val bundle = Bundle()
bundle.putInt("key1", 22)
bundle.putString("key2", "wwwwwwww")
//赋值
fragment.arguments = bundle
//并联关系
val beginTransaction = supportFragmentManager.beginTransaction()
//将某个layout的id拿到,添加到fragment上
beginTransaction.add(R.id.container, fragment)
//添加到事务里面
beginTransaction.commitAllowingStateLoss()
}
}
//Fragment
class FragmentStudy :Fragment(){
var key1 = 2
var key2 = "qqqqq"
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// return inflater.inflate(R.layout.activity_third, container, false)
//创建一个textView
val textView = TextView(context)
textView.text = key2
textView.setTextSize(22F)
textView.gravity = Gravity.CENTER
return textView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
key1 = arguments?.getInt("key1") ?: 3
key2 = arguments?.getString("key2") ?: "pppp"
println("key1 = ${key1}")
println("key2 = ${key2}")
//该view,就是上面创建的TextView
val textView = view as TextView
textView.text = key2
}
}