鄙人由于工作繁忙很久没写博客了还望大家谅解!之前csdn登不上,算了不说借口了,retrofit2相信已经很火了吧,而且上手也比较容易,之前可能大家都是用Volley,Okhttp、Okhttp3其实大同小异,最近由于项目需要,之前大家相信很多人在用鸿神的okhttpUitl工具类,其实鸿神也写过一篇关于Retrofit2的文章感兴趣的童鞋异移步到这里这么晚还开车真是不容易啊!没办法自己太菜了!我去!

注解

retrofit通过使用注解来简化请求,大体分为以下几类:

1.用于标注请求方式的注解

2.用于标记请求头的注解

3.用于标记请求参数的注解

4.用于标记请求和响应格式的注解

请求方法注解

@GET get请求
@PUT put请求
@POST post请求
@PATCH patch请求,该请求是对put请求的补充,用于更新局部资源
@delete delete请求
@HEAD head请求
@OPTIONS option请求
@HTTP 通用注解,可以替换以上所有的注解,其拥有三个属性:method,path,hasBody

请求头注解

注解 说明
@Headers 用于添加固定请求头,可以同时添加多个。通过该注解添加的请求头不会相互覆盖,而是共同存在
@Header 作为方法的参数传入,用于添加不固定值的Header,该注解会更新已有的请求头

请求参数头注解

请求和响应格式注解

简单使用

  1. 首先介绍的是get请求方式
  1. public interface AppInfoStore{
  2. /**Get请求不需要以/开头**/
  3. @GET("index.php?route=app/index/init")
  4. /**Call<T>里面是个泛型所以里面既可以是ReponseBody也可以是String或者JavaBean对象**/
  5. Call<AppInfo> init(@Query("version_code")String version_code);
  6. /**RXJava 观察者**/
  7. @GET("index.php?route=app/index/init")
  8. Observable<AppInfo> initRx(@Query("version_code")String version_code);
  9. }
  1. 第一步创建ApiClient
  2. 利用GsonFormat生成对应的Bean
  3. 然后在主Activity中进行接口联调
  1. package zm.visoport.com.retrofitproject.weather;
  2. import retrofit2.Retrofit;
  3. import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
  4. import retrofit2.converter.gson.GsonConverterFactory;
  5. import retrofit2.http.GET;
  6. import retrofit2.http.Query;
  7. import rx.Observable;
  8. import zm.visoport.com.retrofitproject.register.AppInfo;
  9. /**
  10. * @author zm
  11. */
  12. public class AppInfoClient {
  13. static Retrofit mRetrofit = null;
  14. /**
  15. *创建Retrofit实例并返回
  16. **/
  17. public static Retrofit getAppInfo() {
  18. if (mRetrofit == null) {
  19. mRetrofit = new Retrofit.Builder()
  20. //添加rxjava的支持 .baseUrl("http://www.cnyouyao.com/").addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create())
  21. .build();
  22. }
  23. return mRetrofit;
  24. }
  25. public interface AppInfoStore{
  26. // @GET("index.php?route=app/index/init")
  27. // Call<AppInfo> init(@Query("version_code")String version_code);
  28. @GET("index.php?route=app/index/init")
  29. Observable<AppInfo> initRx(@Query("version_code")String version_code);
  30. }
  31. }

第二步进行bean的创建这里用的是hijson格式化json数据

GsonFormat生成对应Bean实体

  1. package zm.visoport.com.retrofitproject.register;
  2. /**
  3. * @author zm
  4. * bean序列化
  5. */
  6. public class AppInfo implements Serializable {
  7. private AppInfo appInfo;
  8. public AppInfo getAppInfo() {
  9. return appInfo;
  10. }
  11. public void setAppInfo(AppInfo appInfo) {
  12. this.appInfo = appInfo;
  13. }
  14. /**
  15. * code : 200
  16. * data : {"apk_url":"http://www.baidu.com","app_id":"1","date_added":"2017-03-17 23:02:00","date_update":"2017-03-17 23:02:07","is_upload":"1","status":"1","type":"1","upgrade_id":"1","upgrade_point":"有新功能了,快来体验吧!","version_code":"2.1","version_id":"2","version_mini":"1"}
  17. * message : 版本升级信息获取成功
  18. * pager : 1
  19. */
  20. /**服务器状态码 例如200 响应成功**/
  21. private int code;
  22. /**服务器返回的数据 可以是对象 Object 或者数据 Array[]**/
  23. private DataBean data;
  24. /**服务器返回的Message 例如版本升级信息获取成功等**/
  25. private String message;
  26. /**默认只有一页数据 返回1**/
  27. private int pager;
  28. public int getCode() {
  29. return code;
  30. }
  31. public void setCode(int code) {
  32. this.code = code;
  33. }
  34. public DataBean getData() {
  35. return data;
  36. }
  37. public void setData(DataBean data) {
  38. this.data = data;
  39. }
  40. public String getMessage() {
  41. return message;
  42. }
  43. public void setMessage(String message) {
  44. this.message = message;
  45. }
  46. public int getPager() {
  47. return pager;
  48. }
  49. public void setPager(int pager) {
  50. this.pager = pager;
  51. }
  52. public static class DataBean {
  53. /**
  54. * apk_url : http://www.baidu.com
  55. * app_id : 1
  56. * date_added : 2017-03-17 23:02:00
  57. * date_update : 2017-03-17 23:02:07
  58. * is_upload : 1
  59. * status : 1
  60. * type : 1
  61. * upgrade_id : 1
  62. * upgrade_point : 有新功能了,快来体验吧!
  63. * version_code : 2.1
  64. * version_id : 2
  65. * version_mini : 1
  66. */
  67. private String apk_url;
  68. private String app_id;
  69. private String date_added;
  70. private String date_update;
  71. private String is_upload;
  72. private String status;
  73. private String type;
  74. private String upgrade_id;
  75. private String upgrade_point;
  76. private String version_code;
  77. private String version_id;
  78. private String version_mini;
  79. public String getApk_url() {
  80. return apk_url;
  81. }
  82. public void setApk_url(String apk_url) {
  83. this.apk_url = apk_url;
  84. }
  85. public String getApp_id() {
  86. return app_id;
  87. }
  88. public void setApp_id(String app_id) {
  89. this.app_id = app_id;
  90. }
  91. public String getDate_added() {
  92. return date_added;
  93. }
  94. public void setDate_added(String date_added) {
  95. this.date_added = date_added;
  96. }
  97. public String getDate_update() {
  98. return date_update;
  99. }
  100. public void setDate_update(String date_update) {
  101. this.date_update = date_update;
  102. }
  103. public String getIs_upload() {
  104. return is_upload;
  105. }
  106. public void setIs_upload(String is_upload) {
  107. this.is_upload = is_upload;
  108. }
  109. public String getStatus() {
  110. return status;
  111. }
  112. public void setStatus(String status) {
  113. this.status = status;
  114. }
  115. public String getType() {
  116. return type;
  117. }
  118. public void setType(String type) {
  119. this.type = type;
  120. }
  121. public String getUpgrade_id() {
  122. return upgrade_id;
  123. }
  124. public void setUpgrade_id(String upgrade_id) {
  125. this.upgrade_id = upgrade_id;
  126. }
  127. public String getUpgrade_point() {
  128. return upgrade_point;
  129. }
  130. public void setUpgrade_point(String upgrade_point) {
  131. this.upgrade_point = upgrade_point;
  132. }
  133. public String getVersion_code() {
  134. return version_code;
  135. }
  136. public void setVersion_code(String version_code) {
  137. this.version_code = version_code;
  138. }
  139. public String getVersion_id() {
  140. return version_id;
  141. }
  142. public void setVersion_id(String version_id) {
  143. this.version_id = version_id;
  144. }
  145. public String getVersion_mini() {
  146. return version_mini;
  147. }
  148. public void setVersion_mini(String version_mini) {
  149. this.version_mini = version_mini;
  150. }
  151. }
  152. }

第三步接口调用

根据一般请求跟rx请求方式

  1. @OnClick({R.id.btn_retrofit2,R.id.btn_retrofitrx})
  2. public void onViewClicked(View view) {
  3. switch (view.getId()) {
  4. case R.id.btn_retrofit2:
  5. /**获取App版本信息**/
  6. getAppInfo();
  7. // getWeather();
  8. break;
  9. /**RXJava请求方式**/
  10. case R.id.btn_retrofitrx:
  11. getRXAppInfo();
  12. break;
  13. }
  14. }
  1. private void getAppInfo() {
  2. AppInfoClient.AppInfoStore app = AppInfoClient.getAppInfo().create(AppInfoClient.AppInfoStore.class);
  3. Call<AppInfo> call = app.init("2.1");
  4. call.enqueue(new Callback<AppInfo>() {
  5. @Override
  6. public void onResponse(Call<AppInfo> call, Response<AppInfo> response) {
  7. /**请求成功的回调**/
  8. if (response.isSuccessful()) {
  9. String appInfo = response.body().getData().getVersion_code() + "\n" +
  10. response.body().getData().getApk_url() + "\n" +
  11. response.body().getData().getVersion_id() + "\n" +
  12. response.body().getData().getDate_update() + "\n";
  13. tvResult.setText("版本信息如下:"+appInfo);
  14. // tvRetrofit.setText(response.body().getAppInfo().getCode()+"\n"
  15. // +response.body().getMessage()+"\n"+
  16. // response.body().getAppInfo().getPager());
  17. }
  18. }
  19. @Override
  20. public void onFailure(Call<AppInfo> call, Throwable t) {
  21. Log.i(TAG, "onFailure: " + call.request());
  22. /**请求失败的回调**/
  23. }
  24. });
  25. }
  26. private void getRXAppInfo() {
  27. AppInfoClient.AppInfoStore app = AppInfoClient.getAppInfo().create(AppInfoClient.AppInfoStore.class);
  28. // Call<AppInfo> call=app.init("2.1");
  29. final Observable<AppInfo> ob = app.initRx("2.1");
  30. ob.subscribeOn(Schedulers.io())
  31. .observeOn(AndroidSchedulers.mainThread())
  32. .subscribe(new Subscriber<AppInfo>() {
  33. /**请求完成**/
  34. @Override
  35. public void onCompleted() {
  36. Log.i(TAG, "onCompleted: ");
  37. }
  38. /**请求失败**/
  39. @Override
  40. public void onError(Throwable e) {
  41. Log.i(TAG, "onError: " + e.getMessage());
  42. }
  43. //获取网络数据并成功返回
  44. @Override
  45. public void onNext(AppInfo appInfo) {
  46. tvRetrofit.setText("版本号:"+appInfo.getData().getVersion_code());
  47. }
  48. });
  49. }

成功返回数据如图所示

经典文章推荐

《入门篇》

Retrofit2 入门

Retrofit2.0起步篇

Android Retrofit 2.0使用

《进阶篇》

Retrofit2 源码解析

[Retrofit2 完全解析 探索与okhttp之间的关系]

写到最后:

到这里基本的印象已经完成,具体项目还是您自己根据自己的魔板进行分析,很久没写博客了这个点大家应该都睡了!我赶快睡!一直听着外面的雨声滴答滴答跟钟一样,声声入耳!睡觉去了!转载请注明出处http://blog.csdn.net/qq_15950325/article/details/72235028

[置顶] Retrofit2 初印象?的更多相关文章

  1. 在UWP中页面滑动导航栏置顶

    最近在研究掌上英雄联盟,主要是用来给自己看新闻,顺便copy个界面改一下段位装装逼,可是在我copy的时候发现这个东西 当你滑动到一定距离的时候导航栏会置顶不动,这个特性在微博和淘宝都有,我看了@ms ...

  2. WinFrom窗体始终置顶

    调用WindowsAPI使窗体始终保持置顶效果,不被其他窗体遮盖: [DllImport("user32.dll", CharSet = CharSet.Auto)] privat ...

  3. winform窗体置顶

    winform窗体置顶 金刚 winform 置顶 今天做了一个winform小工具.需要设置置顶功能. 网上找了下,发现百度真的很垃圾... 还是必应靠谱些. 找到一个可以链接. https://s ...

  4. 自定义置顶TOP按钮

    简述一下,分为三个步骤: 1. 添加Html代码 2. 调整Css样式 3. 添加Jquery代码 具体代码如下: <style type="text/css"> #G ...

  5. ahk之路:利用ahk在window7下实现窗口置顶

    操作系统:win7 64位 ahk版本:autohotkey_L1.1.24.03 今天安装了AutoHotkey_1.1.24.03.SciTE.PuloversMacroCreator,重新开始我 ...

  6. Qt中让Qwidget置顶的方法

    一般来是说窗体置顶和取消只要        setWindowFlags(Qt::WindowStaysOnTopHint);        setWindowFlags(Qt::Widget); 要 ...

  7. js之滚动置顶效果

    0.js获取高度 ? 1 2 3 4 5 6 document.all   // 只有ie认识   document.body.clientHeight              // 文档的高,屏幕 ...

  8. Javascript笔记----实现Page页面右下角置顶按钮.

    从用博客开始,发现博客园中很多博友的博客中在Page右下角都有个图标,不论屏幕怎么拉伸,都始终停留在右下角.点击后页面置顶.后面想想写一个Demo来实现这种效果吧. 一. 图标右下角固定. 1.SS ...

  9. JavaScript学习笔记-元素在滚动条滑动一定高度后自动置顶

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

随机推荐

  1. PostgreSQL 递归查询 (转)

    数据库中的数据存在父子关系(单继承,每一条记录只有一个父亲).  如果要查询一条记录以及他的所有子记录,或者要查询一条记录以及他的所有父记录.那么递归查询就再合适不过了.可以简化复杂的SQL语句 现在 ...

  2. 再谈CSS动画 - 说点不知道的(一)贝塞尔曲线

    今天重新翻看<CSS 揭秘>"过渡与动画"一章,并把该章代码重新敲了一遍,代码托管在我的Github,在此总结一些心得. 动画的奥秘 在网页中添加动画的目的是让用户有更 ...

  3. mysql系列之多实例介绍

    介绍: mysql多实例,简单理解就是在一台服务器上,mysql服务开启多个不同的端口(如3306.3307),运行多个服务进程.这些 mysql 服务进程通过不同的 socket来监听不同的数据端口 ...

  4. Base64编码原理

    Base64编码之所以称为Base64,是因为其使用64个字符来对任意数据进行编码,同理有Base32.Base16编码.标准Base64编码使用的64个字符为: 这64个字符是各种字符编码(比如AS ...

  5. uboot向linux传递输出任何log信息的方法

    答案:在bootargs中加入loglevel=8即可(在进入linux的过程中会输出任何log信息)

  6. Spring IOC 源码解析(持续)

    如何查看源码 Spring源码下载https://github.com/spring-projects/spring-framework/tags?after=v3.1.0.RC1 eclipse关联 ...

  7. OAuth客户端调用

    public class OAuthClientTest { private HttpClient _httpClient; public OAuthClientTest() { _httpClien ...

  8. win32和x86以及x64的区别

    本来是知道x86和x64的区别的. 今天突然在VS2008上看到一个win32的选项,一下子懵了,这是什么玩意. 百度之,发现答案 win32是指windows 32位的操作系统,顾名思义是支持32为 ...

  9. [Network Architecture]ResNext论文笔记(转)

    文章地址: https://blog.csdn.net/u014380165/article/details/71667916 论文:Aggregated Residual Transformatio ...

  10. matplotlib 初步学习

    author:pprp Matplotlib数据可视化 [TOC] 安装 conda install matplotlib sudo apt-get install python-matplotlib ...