Retrofit 注解参数详解

2024-06-16 08:20
文章标签 参数 详解 注解 retrofit

本文主要是介绍Retrofit 注解参数详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

添加依赖

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

初始化Retrofit

val retrofit = Retrofit.Builder().baseUrl("http://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build()

GET


一个简单的get请求:http://api.github.com/News

 @GET("News")Call<NewsBean> getItem();

@Path

interface ApiService {@GET("users/{user}/repos")fun listRepos(@Path("user") user: String): Call<List<Repo>>
}

创建 ApiService 实例

val service: ApiService = retrofit.create(ApiService::class.java)
service.listRepos("zyj1609wz").execute()

请求url

https://api.github.com/users/zyj1609wz/repos

抓包如下:


@Query


Query参数在URL问号之后

interface ApiService {@GET("users/{user}/repos")fun listRepos(@Path("user") user: String, @Query("sort") sort: String):Call<List<Repo>>
}

抓包如下:


@QueryMap


多个参数在URL问号之后,且个数不确定

interface ApiService {@GET("users/repos")fun listRepos(@QueryMap map: Map<String, String>): Call<List<Repo>>}


POST


@Body


body 传字符串

 @POST("users/repos")fun listRepos(@Body name: String): Call<List<Repo>

body 传对象, retrofit 会自动把对象解析成 json 字符串

@POST("users/repos")
fun listRepos(@Body user: User): Call<List<Repo>>

抓包看结果


form表单1:@FormUrlEncoded 、@Field


Form 表单提交数据, 数据也是放在 body 里面,通常 Form 表单和 @Field 注解联合使用。

Content-Type:application/x-www-form-urlencoded
使用 form表单提交数据,首先要在接口方法上添加 @FormUrlEncoded 注解。参数使用 @Field 、 @FieldMap

@POST("users/repos")
@FormUrlEncoded
fun listRepos(@Field("name") name: String): Call<List<Repo>>

抓包来看结果:

body 数据如下:name=zhaoyanjun

多个 @Field 字段

@POST("users/repos")
@FormUrlEncoded
fun listRepos(@Field("name") name: String, @Field("age") age: Int): Call<List<Repo>>

抓包看结果:

body 数据格式如下:name=zhaoyanjun&age=20

多个参数除了用多个 @Field ,还可以用 @FieldMap

@POST("users/repos")
@FormUrlEncoded
fun listRepos(@FieldMap name: Map<String, String>): Call<List<Repo>>

form表单2:FormBody
出了上面的 @FormUrlEncoded 我们还可以使用 FormBody 的方式提交。

首先定义接口:

@POST("users/repos")
fun listRepos(@Body body: RequestBody): Call<List<Repo>>

构建 FormBody

val body = FormBody.Builder().add("name", "zhaoyanjun").add("age", "20").build()service.listRepos(body).execute()

结果如下:

可以看到 Content-Type: application/x-www-form-urlencoded
body 参数是:name=zhaoyanjun&age=20

完美实现 form 表单提交数据。

@Multipart


其实无论什么库,只要是发送 Http 请求,都得遵守 Http 协议,所以熟悉协议内容对理解库原理、调试是有很大帮助的。

Http 上传协议为 MultiPart。下面是通过抓包获取的一次多文件+文本的上传消息,每行前面的行数是为了标注说明方便加上的,实际请求中没有。

上传单个文件

@POST("find")
@Multipart
fun listRepos(@Part part: MultipartBody.Part): Call<List<Repo>>

使用:

val file = File(externalCacheDir?.absolutePath + File.separator + "123.txt")
val requestFile = file.asRequestBody()
//创建 Part
val filePart = MultipartBody.Part.createFormData("file", file.name, requestFile)//发起请求
service.listRepos(filePart).execute()

抓包看结果:

Content-Type: multipart/form-data; boundary=fa722b45-62ed-4481-a9fa-8b5812686d0c


上传多个文件

【方式一】
第一种方式, 写多个 MultipartBody.Part ,比如:

@POST("find")
@Multipart
fun listRepos(@Part part: MultipartBody.Part, @Part part2: MultipartBody.Part): Call<List<Repo>>

使用:

//创建第一个 Part
val file = File(externalCacheDir?.absolutePath + File.separator + "123.txt")
val requestFile = file.asRequestBody()
val filePart = MultipartBody.Part.createFormData("file", file.name, requestFile)//创建第二个 Part
val file2 = File(externalCacheDir?.absolutePath + File.separator + "456.txt")
val requestFile2 = file2.asRequestBody()
val filePart2 = MultipartBody.Part.createFormData("file2", file2.name, requestFile2)//执行
service.listRepos(filePart, filePart2).execute()

抓包看结果:

上传多个文件【方式二】

@POST("find")
fun listRepos(@Body body: MultipartBody): Call<List<Repo>>

使用

//创建第一个 Part
val file = File(externalCacheDir?.absolutePath + File.separator + "123.txt")
val requestFile = file.asRequestBody()
val filePart = MultipartBody.Part.createFormData("file", file.name, requestFile)//创建第二个 Part
val file2 = File(externalCacheDir?.absolutePath + File.separator + "456.txt")
val requestFile2 = file2.asRequestBody()
val filePart2 = MultipartBody.Part.createFormData("file2", file2.name, requestFile2)//构建 body 
val body = MultipartBody.Builder().setType(MultipartBody.FORM)// .addFormDataPart("file", file.name, requestFile)    .addPart(filePart)//  .addFormDataPart("file2", file2.name, requestFile2)           .addPart(filePart2).build()//发起请求
service.listRepos(body).execute()

复核参数
构建普通参数的 Part

val part = MultipartBody.Part.createFormData("age", "20")//或者
val body = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("age", "20").build()

@Header


添加 Header 方式一

@POST("find")
fun listRepos(@Header("Accept-Encoding") encoding: String): Call<List<Repo>>

抓包看结果

添加多个 Header , 使用 @HeaderMap

@POST("find")
fun listRepos(@HeaderMap headers: Map<String, String>): Call<List<Repo>>

添加 Header 方式二
单个参数

@POST("find")
@Headers("token:zhaoyanjun")
fun listRepos(): Call<List<Repo>>

多个参数

@Headers("name:zhaoyanjun", "age:20")
@POST("find")
fun listRepos(): Call<List<Repo>>

添加 Header 方式三:拦截器

private val client = OkHttpClient.Builder().addInterceptor(HeaderInterceptor()).build()private val retrofit = Retrofit.Builder().baseUrl("http://10.8.67.211:8080").client(client).addConverterFactory(GsonConverterFactory.create()).build()class HeaderInterceptor : Interceptor {override fun intercept(chain: Interceptor.Chain): okhttp3.Response {val oldRequest = chain.request()val builder = oldRequest.newBuilder()builder.addHeader("name", "zhaoyanjun")builder.addHeader("age", "20")val request = builder.build()return chain.proceed(request)}
}

添加 Header 方式四:Request

val client = OkHttpClient.Builder().build()val request = Request.Builder().url("http://www..").addHeader("name", "zhaoyanjun").addHeader("age", "20").build()client.newCall(request).execute()


                        
原文链接:https://blog.csdn.net/zhaoyanjun6/article/details/121000230

这篇关于Retrofit 注解参数详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1065936

相关文章

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

一文详解MySQL如何设置自动备份任务

《一文详解MySQL如何设置自动备份任务》设置自动备份任务可以确保你的数据库定期备份,防止数据丢失,下面我们就来详细介绍一下如何使用Bash脚本和Cron任务在Linux系统上设置MySQL数据库的自... 目录1. 编写备份脚本1.1 创建并编辑备份脚本1.2 给予脚本执行权限2. 设置 Cron 任务2

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

mapstruct中的@Mapper注解的基本用法

《mapstruct中的@Mapper注解的基本用法》在MapStruct中,@Mapper注解是核心注解之一,用于标记一个接口或抽象类为MapStruct的映射器(Mapper),本文给大家介绍ma... 目录1. 基本用法2. 常用属性3. 高级用法4. 注意事项5. 总结6. 编译异常处理在MapSt

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF

CSS3中的字体及相关属性详解

《CSS3中的字体及相关属性详解》:本文主要介绍了CSS3中的字体及相关属性,详细内容请阅读本文,希望能对你有所帮助... 字体网页字体的三个来源:用户机器上安装的字体,放心使用。保存在第三方网站上的字体,例如Typekit和Google,可以link标签链接到你的页面上。保存在你自己Web服务器上的字