Retrofit--官网2.1.0
Retrofit--官网2.1.0
介绍
Retrofit 将 HTTP API 转换为 Java 的接口:
- public interface GitHubService {
- @GET("users/{user}/repos")
- Call<List<Repo>> listRepos(@Path("user") String user);
- }
使用 Retrofit 类生成 GitHubService 的实例:
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("https://api.github.com/")
- .build();
- GitHubService service = retrofit.create(GitHubService.class);
在 GitHubService 实例上的每次调用都会产生一个到远程服务的同步、或异步的 HTTP 的请求:
- Call<List<Repo>> repos = service.listRepos("octocat");
使用注解描述 HTTP 请求:
支持
URL参数的占位符,支持请求参数对象和
response body的转换(例如:JSON等)Multipart请求体和文件上传
API 描述
接口方法和参数上的注解标识了如何处理一个请求。
请求方法
每个方法必须使用一个注解来提供请求类型和相对 URL 地址。请求类型注解一共有五个:GET,POST,PUT,DELETE,HEAD。注解中也可以指定相对的 URL 地址:
- @GET("users/list")
在 URL 中,也可以指定查询参数:
- @GET("users/list?sort=desc")
URL 处理
请求的 URL 中,可以使用占位符块和方法中的参数,对 URL 进行动态的更新。一个占位符块就是在 { 和 } 之间包含的数字和字母。必须使用同样的数字和字母,使用 @Path 注解来申明相应的参数:
- @GET("group/{id}/users")
- Call<List<User>> groupList(@Path("id") int groupId);
当然,也可以添加查询参数:
- @GET("group/{id}/users")
- Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
复杂的查询参数(例如 Map 类型)的示例:
- @GET("group/{id}/users")
- Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
请求体
可以使用 @Body 注解来把一个对象指定为 HTTP 的 BODY:
- @GET("group/{id}/users")
- Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
也可以通过给 Retrofit 的实例指定转换器的方式对对象进行转换。如果没有添加转换器,仅能使用 RequestBody。
表单的 ENCODED 和 MULTIPART
也可以申明方法来发送 form-encoded 和 multipart 的数据。
当方法上存在 @FormUrlEncoded 注解时,就会发送 form-encoded 的数据。@Filed 包含了键值对的键名称,后面的对象提供了键值对的值:
- @FormUrlEncoded
- @POST("user/edit")
- Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
当方法上存在 @Multipart 注解时,就会发送 multipart 的数据,各部分使用 @Part 注解进行申明:
- @Multipart
- @PUT("user/photo")
- Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
multipart 的各部分要么使用 Retrofit 的转换器,要么实现 RequestBody,用这样的方式来实现各自的序列化。
HEADER 处理
可以使用 @Headers 注解来为某个方法设置静态的头:
- @Headers("Cache-Control: max-age=640000")
- @GET("widget/list")
- Call<List<Widget>> widgetList();
- @Headers({
- "Accept: application/vnd.github.v3.full+json",
- "User-Agent: Retrofit-Sample-App"
- })
- @GET("users/{username}")
- Call<User> getUser(@Path("username") String username);
注意:header中的各个部分不能相互覆盖。所有相同名称的header都会被包含在请求中。
也可以使用 @Header 注解对头部内容进行动态的更新。对应的参数必须由 @Header 进行提供。如果值为 null,那么将被忽略。如果不为 null,值将会使用 toString() 方法,最终使用 toString() 方法返回的值:
- @GET("user")
- Call<User> getUser(@Header("Authorization") String authorization)
如果要给每个请求都添加头部,那么,可以使用 OkHttp interceptor 进行指定。
同步 VS 异步
Call 对象的实例上,即可以使用同步,也可以使用异步。它的每个实例只能使用一次,使用 clone() 方法就可以创建一个新的实例来使用。
在 Android 中,回调方法会在主线程中执行。在 JVM 中,回调将和执行 HTTP 请求发生在同一线程。
Retrofit 配置
默认地,Retrofit 有健全的默认值,但是,也可以自定义配置。
转换器
默认地,Retrofit 只会把 HTTP body 的内容反序列化到 OKHttp 的 ResponseBody 类型中,并且它只接收用 @Body 标注的 RequestBody 类型。
要支持其它的类型,可以添加转换器。为了方便起见,为了适配一些流行的序列化库,Retrofit 已经提供了六个模块:
Gson: com.squareup.retrofit2:converter-gsonJackson: com.squareup.retrofit2:converter-jacksonMoshi: com.squareup.retrofit2:converter-moshiProtobuf: com.squareup.retrofit2:converter-protobufWire: com.squareup.retrofit2:converter-wireSimple XML: com.squareup.retrofit2:converter-simplexmlScalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
下面的示例中,使用 GsonConverterFactory 类来生成 GitHubService 的实现,该实现使用 Gson 作为反序列化的工具:
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("https://api.github.com")
- .addConverterFactory(GsonConverterFactory.create())
- .build();
- GitHubService service = retrofit.create(GitHubService.class);
自定义转换器
如果你需要与之通信的 API 使用了 Retrofit 不支持的内容格式(例如:YAML,文本,自定义格式等),或者你想使用一个其它的库来实现一个已经存在的格式,那么,就需要创建自己的转换器,这是一件非常简单的事情。创建一个类继承 Converter.Factory 类,然后,在构建适配器时,把它传给实例就可以了。
下载
使用 maven
- <dependency>
- <groupId>com.squareup.retrofit2</groupId>
- <artifactId>retrofit</artifactId>
- <version>2.1.0</version>
- </dependency>
使用 Gradle
- compile 'com.squareup.retrofit2:retrofit:2.1.0'
注意:Retrofit 需要 Java 7 及以上,Android 2.3 及以上
PROGUARD
如果项目使用了 Proguard,需要把下面的内容添加到项目的配置中:
- # Platform calls Class.forName on types which do not exist on Android to determine platform.
- -dontnote retrofit2.Platform
- # Platform used when running on RoboVM on iOS. Will not be used at runtime.
- -dontnote retrofit2.Platform$IOS$MainThreadExecutor
- # Platform used when running on Java 8 VMs. Will not be used at runtime.
- -dontwarn retrofit2.Platform$Java8
- # Retain generic type information for use by reflection by converters and adapters.
- -keepattributes Signature
- # Retain declared checked exceptions for use by a Proxy instance.
- -keepattributes Exceptions
Retrofit--官网2.1.0的更多相关文章
- [ActionScript 3.0] Away3D 官网实例
/* Dynamic tree generation and placement in a night-time scene Demonstrates: How to create a height ...
- vue2.0实践 —— Node + vue 实现移动官网
简介 使用 Node + vue 对公司的官网进行了一个简单的移动端的实现. 源码 https://github.com/wx1993/node-vue-fabaocn 效果 组件 轮播图(使用 vu ...
- i春秋官网4.0上线啦 文末有福利
爱瑞宝地(Everybody)期待了很久的 i春秋官网4.0上线啦 除了产品的功能更加完善 性能和体验也将大幅度提高 清新.舒适的视觉感受 搭配更加便捷的操作流程 只需一秒,扫码立即登录 即刻进入网络 ...
- Navicat Premium 简体中文版 12.0.16 以上版本国外官网下载地址(非国内)
国内Navicat网址是:http://www.navicat.com.cn 国外Navicat网址是:http://www.navicat.com 国外的更新比国内的快,而且同一个版本,国内和国外下 ...
- 使用 php 7.3.0 官网的压缩包安装 FastAdmin
使用 php 7.3.0 官网的压缩包安装 FastAdmin 直接从 php.net 官网下载了一 php7.3.0 的压缩包,解压到 c:/temp/php73 目录. 将 c:/temp/php ...
- 【转】MyEclipse 9.0正式版官网下载(附Win+Llinux激活方法、汉化包)
MyEclipse 9.0 经过 M1,M2,终于出了正式版(MyEclipse For Spring 还是 8.6.1).该版本集成了 Eclipse 3.6.1,支持 HTML5 和 JavaEE ...
- 从谷歌官网下载android 6.0源码、编译并刷入nexus 6p手机
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/fuchaosz/article/details/52473660 1 前言 经过一周的奋战,终于从谷 ...
- 2022年官网下安装Logstash最全版与官网查阅方法(8.1.0最新安装)
一.环境整合 构建工具(参考工具部署方式) 软件名称 版本 相关文章推荐 NodeJS 16.0.0 https://www.cnblogs.com/liuyangfirst/p/15998172.h ...
- 2022年官网下安装Elasticsearch最全版与官网查阅方法(8.1.0最新安装)
目录 一.环境整合(需要提前装好) 构建工具(参考工具部署方式) 二.官方下载Elasticsearch部署安装 1.百度搜索"Elasticsearch",或者访问官网https ...
- 0. 资料官网【从零开始学Spring Boot】
[视频&交流平台] àSpringBoot视频 http://study.163.com/course/introduction.htm?courseId=1004329008&utm ...
随机推荐
- ab并发负载压力测试
一.ab 0.安装ab压力测试软件 [root@a2 conf]# yum install httpd-tools -y #查看版本 [root@a2 conf]# ab -V This is Apa ...
- sqlite developer注册码
sqlite developer注册码网上没有找到,只有通过注册表,删除继续使用,删除注册表中 HKEY_CURRENT_USER\SharpPlus\SqliteDev.
- BEGINNING SHAREPOINT® 2013 DEVELOPMENT 第9章节--client对象模型和REST APIs概览 Windows Phone
BEGINNING SHAREPOINT® 2013 DEVELOPMENT 第9章节--client对象模型和REST APIs概览 Windows Phone 和.NET托管代码和 ...
- Office办公 如何打印顺丰发票
1 关注顺丰速递,我-我的钱包 2 我的钱包-发票申请 3 勾选要打印发票的项目,点击申请发票 4 点击提交,确认发送的邮箱(他是把PDF发到指定邮箱) 最后PDF效果如下 ...
- 使用iOS-QR-Code-Encoder 生成二维码
一:所需类库 iOS-QR-Code-Encoder 官网主页:https://github.com/moqod/iOS-QR-Code-Encoder 导入:QuartzCore.framework ...
- 一个.net Cookie组件的bug引发的题外话
在.net里,做过Http模拟发送请求的朋友们应该遇到过,有个时候无论怎么努力,都没办法让Cookie跟网页用浏览器所收集的一样,其中原因除了有些Cookie大概是ReadOnly之外,似乎另有隐情: ...
- Gradle在Android中的基本使用
1.基本概念 程序开发作为一种工程作业,不光是编写代码,还涉及到工程的各种管理(依赖,打包,部署,发布,各种渠道的差异管理.....).很多时候,我们反复的build,clean,签名,打包,发布,那 ...
- [Exception IOS 4] - could not build module 'foundation'
出现这个问题首先百度找到的是:http://www.cocoachina.com/bbs/read.php?tid=188086 然后在blog中能找到链接:http://stackoverflow. ...
- 【Python 数据分析】从Mysql数据库取出数据作图分析
在之前的文章中[爬取天气信息]我们已经将昆明二月份的气温爬取到数据库了,那么现在我们需要对这些数据进行一些分析操作,下面是使用matplotlib对这些数据的一些操作 折线图 首先我们读取数据库中的数 ...
- nginx 反向代理做域名转发简单配置
这里用的是nginx for windows 首先进入nginx配置文件,做以下配置: server { listen 80; server_name abc.com; location / { pr ...