IT评测·应用市场-qidao123.com

标题: 安卓笔记1-Retrofit2请求自界说接口 [打印本页]

作者: 我可以不吃啊    时间: 2024-7-14 20:05
标题: 安卓笔记1-Retrofit2请求自界说接口
1、团体功能概述

   安卓项目中使用Retrofit2实现和自界说接口的网络交互,通过Postman模仿服务端,创建自界说接口。
  作用

缺点


2、postman mock接口

使用Postman mock 同一URL下差别的功能接口,表示如下:
  1. // 功能接口URL
  2. https://myapi.com/myservice1
  3. https://myapi.com/myservice2
  4. https://myapi.com/myservice3
  5. ...
复制代码
注:https: //myapi.com/会被替换成postman天生的URL,最终可调用的完备URL长这样:
https://随机天生的字符串.mock.pstmn.io/myservice
流程


完成后点击右下角 next


点击右上角 view Collection Docs查看接口信息

如上,模仿天生了一个url下两个差别的功能接口,按还是例访问即可。
3、Retrofit2举行网络交互

   在Android项目(本文以空缺项目为例)中设置retrofit2
  项目团体结构

如下图所示:

1)首先配置Retrofit客户端
  1. // RetrofitClient.kt
  2. package com.example.retrofit
  3. import retrofit2.Retrofit
  4. import retrofit2.converter.gson.GsonConverterFactory
  5. object RetrofitClient {
  6.     private const val SERVICE_BASE_URL = "https://你生成的随机字符串.mock.pstmn.io"
  7.   // 配置retrofit实例
  8.     val serviceRetrofit: Retrofit by lazy {
  9.         Retrofit.Builder()
  10.             .baseUrl(SERVICE_BASE_URL)
  11.             .addConverterFactory(GsonConverterFactory.create())
  12.             .build()
  13.     }
  14.   
  15.         //配置接口实例
  16.     val service1: Service1 by lazy {
  17.         serviceRetrofit.create(Service1::class.java)
  18.     }
  19.     val service2: Service2 by lazy {
  20.         serviceRetrofit.create(Service2::class.java)
  21.     }
  22.    
  23. }
复制代码
2)配置接口
  1. // ApiService.kt
  2. package com.example.retrofit
  3. import retrofit2.Call
  4. import retrofit2.http.GET
  5. // 配置接口协议方法、路径、响应
  6. interface Service1 {
  7.     @GET("/myservice1")
  8.     fun getService1(): Call<Service1Response>
  9. }
  10. interface Service2 {
  11.     @GET("/myservice2")
  12.     fun getService2(): Call<Service2Response>
  13. }
复制代码
3)相应体数据类
   业务中接口数据通常会非常复杂,建议使用GsonJsonObject简化相应体。
  本文举例的相应较为简单。
  1. /**
  2. * Response.kt
  3. * @tip: 根据响应体设置数据类
  4. */
  5. package com.example.retrofit
  6. data class Service1Response(
  7.     val goal1: String
  8. )
  9. data class Service2Response(
  10.     val goal2: String
  11. )
复制代码
4)请求体类
   仅测试用,无特殊要求可以不写。
  5)调用
xml
  1. <!--  activity_main.xml  -->
  2. <?xml version="1.0" encoding="utf-8"?>
  3. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  4.     android:layout_width="match_parent"
  5.     android:layout_height="match_parent"
  6.     android:orientation="vertical"
  7.     android:gravity="center"
  8.     android:padding="16dp">
  9.     <TextView
  10.         android:id="@+id/textView1"
  11.         android:layout_width="wrap_content"
  12.         android:layout_height="wrap_content"
  13.         android:text="Response from Service 1"
  14.         android:layout_marginBottom="10dp"/>
  15.     <TextView
  16.         android:id="@+id/textView2"
  17.         android:layout_width="wrap_content"
  18.         android:layout_height="wrap_content"
  19.         android:text="Response from Service 2"/>
  20. </LinearLayout>
复制代码
MainActivity
  1. package com.example.testretrofit
  2. import androidx.appcompat.app.AppCompatActivity
  3. import android.os.Bundle
  4. import android.widget.TextView
  5. import com.example.retrofit.RetrofitClient
  6. import com.example.retrofit.Service1Response
  7. import com.example.retrofit.Service2Response
  8. import retrofit2.Call
  9. import retrofit2.Callback
  10. import retrofit2.Response
  11. class MainActivity : AppCompatActivity() {
  12.     private lateinit var textView1: TextView
  13.     private lateinit var textView2: TextView
  14.     override fun onCreate(savedInstanceState: Bundle?) {
  15.         super.onCreate(savedInstanceState)
  16.         setContentView(R.layout.activity_main)
  17.         textView1 = findViewById(R.id.textView1)
  18.         textView2 = findViewById(R.id.textView2)
  19.         RetrofitClient.service1.getService1().enqueue(object : Callback<Service1Response> {
  20.             override fun onResponse(call: Call<Service1Response>, response: Response<Service1Response>) {
  21.                 if (response.isSuccessful) {
  22.                     println("getService1调用成功")
  23.                     println(response.body())
  24.                     runOnUiThread {
  25.                         response.body()?.let {
  26.                             textView1.text = it.goal1
  27.                         }
  28.                     }
  29.                 } else {
  30.                     // 处理错误响应
  31.                     println("getService1响应错误")
  32.                 }
  33.             }
  34.             override fun onFailure(call: Call<Service1Response>, t: Throwable) {
  35.                 // 处理请求失败
  36.                 println("getService1响应失败")
  37.             }
  38.         })
  39.         RetrofitClient.service2.getService2().enqueue(object : Callback<Service2Response> {
  40.             override fun onResponse(call: Call<Service2Response>, response: Response<Service2Response>) {
  41.                 if (response.isSuccessful) {
  42.                     println("getService2调用成功")
  43.                     println(response.body())
  44.                     runOnUiThread {
  45.                         response.body()?.let {
  46.                             textView2.text = it.goal2
  47.                         }
  48.                     }
  49.                 } else {
  50.                     // 处理错误响应
  51.                     println("getService2响应错误,状态码: ${response.code()}, 错误信息: ${response.message()}")
  52.                 }
  53.             }
  54.             override fun onFailure(call: Call<Service2Response>, t: Throwable) {
  55.                 // 处理请求失败
  56.                 println("getService2响应失败,错误: ${t.message}")
  57.             }
  58.         })
  59.     }
  60. }
复制代码
实测

   模仿器肯定肯定选择新一点的api版本!

  不然跟我一样和GPT怒耗半天

  


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4