retrofit使用技巧

1. 发送表单数据(Form-Encoded)

当需要向服务器提交表单数据时,可以使用 @FormUrlEncoded 和 @Field 或 @FieldMap 注解。
@FormUrlEncoded 注解用于标识请求体为表单编码格式。
@Field 注解用于指定表单字段的名称和值。


// 定义 API 接口
interface ApiService { 
 @FormUrlEncoded 
 @POST("login")
 fun login(@Field("username") username: String,@Field("password") password: String
   ): Call<LoginResponse>
}

// 响应数据类
data class LoginResponse(val message: String)

// 使用示例
fun main() {
    val retrofit = Retrofit.Builder()
       .baseUrl("https://example.com/")
       .addConverterFactory(GsonConverterFactory.create())
       .build()

    val apiService = retrofit.create(ApiService::class.java)
    val call = apiService.login("testuser", "testpassword")
    call.enqueue(object : retrofit2.Callback<LoginResponse> {
        override fun onResponse(
            call: Call<LoginResponse>,
            response: retrofit2.Response<LoginResponse>
        ) {
            if (response.isSuccessful) {
                val loginResponse = response.body()
                println("登录成功: ${loginResponse?.message}")
            } else {
                println("登录失败: ${response.code()}")
            }
        }

        override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
            println("请求出错: ${t.message}")
        }
    })
}
  1. 发送 JSON 数据
    如果需要发送 JSON 格式的数据,可以使用 @Body 注解将一个对象作为请求体发送。
    @Body 注解用于将 LoginRequest 对象作为请求体发送,Retrofit 会自动将对象转换为 JSON 格式。

// 请求数据类
data class LoginRequest(val username: String, val password: String)

// 响应数据类
data class LoginResponse(val message: String)

// 定义 API 接口
interface ApiService {
    @POST("login")
    fun login(@Body loginRequest: LoginRequest): Call<LoginResponse>
}

// 使用示例
fun main() {
    val retrofit = Retrofit.Builder()
       .baseUrl("https://example.com/")
       .addConverterFactory(GsonConverterFactory.create())
       .build()

    val apiService = retrofit.create(ApiService::class.java)
    val loginRequest = LoginRequest("testuser", "testpassword")
    val call = apiService.login(loginRequest)
    call.enqueue(object : retrofit2.Callback<LoginResponse> {
        override fun onResponse(
            call: Call<LoginResponse>,
            response: retrofit2.Response<LoginResponse>
        ) {
            if (response.isSuccessful) {
                val loginResponse = response.body()
                println("登录成功: ${loginResponse?.message}")
            } else {
                println("登录失败: ${response.code()}")
            }
        }

        override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
            println("请求出错: ${t.message}")
        }
    })
}
  1. 发送多部分数据(Multipart)
    当需要上传文件或同时上传文件和其他表单数据时,可以使用 @Multipart、@Part 或 @PartMap 注解。
    @Multipart 注解用于标识请求体为多部分表单数据。
    @Part 注解用于指定每个部分的数据,如文件或表单字段。
// 响应数据类
data class UploadResponse(val message: String)

// 定义 API 接口
interface ApiService {
    @Multipart
    @POST("upload")
    fun uploadFile(
        @Part file: MultipartBody.Part,
        @Part("description") description: RequestBody
    ): Call<UploadResponse>
}

// 使用示例
fun main() {
    val retrofit = Retrofit.Builder()
       .baseUrl("https://example.com/")
       .addConverterFactory(GsonConverterFactory.create())
       .build()

    val apiService = retrofit.create(ApiService::class.java)

    // 创建文件请求体
    val file = java.io.File("path/to/your/file.jpg")
    val requestFile = RequestBody.create(okhttp3.MediaType.parse("image/jpeg"), file)
    val filePart = MultipartBody.Part.createFormData("file", file.name, requestFile)

    // 创建描述请求体
    val description = RequestBody.create(okhttp3.MediaType.parse("text/plain"), "This is a test file")

    val call = apiService.uploadFile(filePart, description)
    call.enqueue(object : retrofit2.Callback<UploadResponse> {
        override fun onResponse(
            call: Call<UploadResponse>,
            response: retrofit2.Response<UploadResponse>
        ) {
            if (response.isSuccessful) {
                val uploadResponse = response.body()
                println("上传成功: ${uploadResponse?.message}")
            } else {
                println("上传失败: ${response.code()}")
            }
        }

        override fun onFailure(call: Call<UploadResponse>, t: Throwable) {
            println("请求出错: ${t.message}")
        }
    })
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容