Retrofit 初步的使用
2016-12-09 21:45
471 查看
这篇文章主要是一篇 Retrofit 使用的初级案例,案例的源码放在我的 Github上,希望能帮到像我一样的初学者。
就好像人跟人之间需要通过语言来沟通,客户端/浏览器 跟 服务器之间也需要通过某种语言来沟通,这种语言通常就是 Http。
就好像人有头和身体一样,Http 也有头,也就是 Http Headers,也有身体,就是 Http body。Http Headers 是 Http 协议的核心部分。
每一门语言都有语法结构。Http 协议也有相应的消息结构。
参考链接:
文章1;
文章2;
文章3;
文章4。
看完并理解这四篇文章,不能让你成为Http方面的专家,但相信你在阅读 Retrofit 相关教程的时候不会一头雾水了。
GET
用于从服务器获取数据
POST
用于向服务器传递数据
Retrofit 通过注解将 Http 请求方法以及其他的参数表示出来。
@GET、@POST 具有 Http 方法的功能。
@Query 用于查询参数,它有两种形式:
第一种:
第二种(id加在
这两种方式是等价的。
@Path 用于 url 上的占位符
这是官网的例子:
关于 Retrofit 注解的详细解释,可以查看这篇文章。
能够将一个 Http API 转换成一个 接口。
适用于与 Web 服务器提供的 API 接口进行通信。
这里的
在 gradle 中加入如下依赖:
在 Android studio 中可以通过 File/project structure/app/dependencies 来添加所需依赖。
在 manifest.xml 中加入网络权限:
根据要返回的
不带 id 时,
带有 id 时:
这里提供一个将 Json 格式的数据转为 Java 实体类的神器:Json 转 Java
得到结果后只需要进行一些简单的调整就可以了,超级方便。
我上面的 GET 请求的 Model 和 下面的 POST 请求的 Model 都是由此写出的。
在接口中,有些知识点在这里说明一下(以第一个接口为例):
下面就是重头戏了:
运行结果如下:
最后:
Retrofit 适用于 Java 7 及 Android 2.3 以上的版本。不过现在大多数版本都是符合要求的。
作为一个初学者,我认为在学习过程中最需要的是理论+实践,理论的部分很多博客都写到了,所以我自己写博客喜欢带有案例。我认为,独立写出一个运行成功的 demo ,对于理解知识点是非常重要的。
希望这篇文章能对大家的学习有所帮助。
Http 基础知识
这里列出了一些我在学习时使用的参考资料,写的都非常好,所以我直接附上链接了。就好像人跟人之间需要通过语言来沟通,客户端/浏览器 跟 服务器之间也需要通过某种语言来沟通,这种语言通常就是 Http。
就好像人有头和身体一样,Http 也有头,也就是 Http Headers,也有身体,就是 Http body。Http Headers 是 Http 协议的核心部分。
每一门语言都有语法结构。Http 协议也有相应的消息结构。
参考链接:
文章1;
文章2;
文章3;
文章4。
看完并理解这四篇文章,不能让你成为Http方面的专家,但相信你在阅读 Retrofit 相关教程的时候不会一头雾水了。
Http 方法
本文只涉及到如下两个方法:GET
用于从服务器获取数据
POST
用于向服务器传递数据
Retrofit 通过注解将 Http 请求方法以及其他的参数表示出来。
@GET、@POST 具有 Http 方法的功能。
@Query 用于查询参数,它有两种形式:
第一种:
@GET("param") Call<ParamGetWithId> get(@Query("id") String withId);
第二种(id加在
param之后的问号后面)
@GET("param?id=withId") Call<ParamGetWithId> get(@Query("id") String withId);
这两种方式是等价的。
@Path 用于 url 上的占位符
这是官网的例子:
public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); }
关于 Retrofit 注解的详细解释,可以查看这篇文章。
Retrofit 是什么?
Retrofit is a type safe HTTP client for Android and java.能够将一个 Http API 转换成一个 接口。
适用于与 Web 服务器提供的 API 接口进行通信。
通过案例体会
准备工作
这里提供了三个 Retrofit 测试接口,我选择 param 接口作为测试,接口形式如下:http://retrofit.devwiki.net/param
这里的
http://retrofit.devwiki.net/为
baseUrl,这在后文中要用到。
在 gradle 中加入如下依赖:
compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0'
在 Android studio 中可以通过 File/project structure/app/dependencies 来添加所需依赖。
在 manifest.xml 中加入网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
正式开始
Model部分:
1.GET 请求的 Model:根据要返回的
json格式的数据编写
Model类
不带 id 时,
public class ParamGet { private int code; private String desc; public void setCode(int code){ this.code = code; } public int getCode(){ return this.code; } public void setDesc(String desc){ this.desc = desc; } public String getDesc(){ return this.desc; } }
带有 id 时:
public class ParamGetWithId { private int code; private String desc; private Data data; public void setCode(int code){ this.code = code; } public int getCode(){ return this.code; } public void setDesc(String desc){ this.desc = desc; } public String getDesc(){ return this.desc; } public void setData(Data data){ this.data = data; } public Data getData(){ return this.data; } public static class Data { private String id; public void setId(String id){ this.id = id; } public String getId(){ return this.id; } } }
这里提供一个将 Json 格式的数据转为 Java 实体类的神器:Json 转 Java
得到结果后只需要进行一些简单的调整就可以了,超级方便。
我上面的 GET 请求的 Model 和 下面的 POST 请求的 Model 都是由此写出的。
POST 请求的 Model:
public class ParamPost { private int code; private String desc; private Data data; public void setCode(int code){ this.code = code; } public int getCode(){ return this.code; } public void setDesc(String desc){ this.desc = desc; } public String getDesc(){ return this.desc; } public void setData(Data data){ this.data = data; } public Data getData(){ return this.data; } public static class Data { private String id; private String type; public void setId(String id){ this.id = id; } public String getId(){ return this.id; } public void setType(String type){ this.type = type; } public String getType(){ return this.type; } } }
2.接口部分
public interface ParamInterface { /*GET请求接口*/ //不带 id 时: @GET("param") Call<ParamGet> get(); //带有 id 时: @GET("param") Call<ParamGetWithId> get(@Query("id") String id); //等价于: //@GET("param?id=withId") //Call<ParamGetWithId> get(@Query("id") String withId); /*POST请求接口*/ //不带 id 时: @POST("param") Call<ParamPost> post(@Header("type") String type); // 带有 id 时: @POST("param") Call<ParamPost> post(@Header("type") String type,@Query("id") String id); }
在接口中,有些知识点在这里说明一下(以第一个接口为例):
@Get是指发送一个 Get 请求,
baseUrl + "param"就是 Get 请求的地址。
(@Query("id) String id)表明将通过
baseUrl + "param"这个接口来查询传入的id。
Call<ParamGet>说明
get是一个请求对象,
<ParamGet>表明
get要请求的是一个
ParamGet类型的实例。
下面就是重头戏了:
Retrofit 部分
这里直接贴上代码,然后在代码中通过注释来解释:public class MainActivity extends AppCompatActivity { //关于base_Url 是否以‘/’结尾的问题,看个人习惯,我是选用 Retrofit 官网的写法的。 //(我在学习Retrofit的过程中,有一次没有以‘/’结尾,程序报错了,后来却无法复现这个过程。) private static final String BASE_URL = "http://retrofit.devwiki.net/"; /**这些TAG用来对返回结果进行标记,以便于区分*/ private static final String TAG1 = "Param GET "; private static final String TAG2 = "Param GETWithId "; private static final String TAG3 = "Param POST "; private static final String TAG4 = "Param POSTWithId"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 创建了一个 Retrofit 对象 Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create())//这里添加了一个Gson转换器,用于将对象的序列化和反序列化。 .build(); ParamInterface paramInterface = retrofit.create(ParamInterface.class);// 通过 retrofit 创建了一个接口对象 // Interface 实例调用方法生成 Call<Model> 对象 final Call<ParamGet> paramGet = paramInterface.get();// GET ,不带 id final Call<ParamGetWithId> paramGetWithId = paramInterface.get("123");// GET,带有 id final Call<ParamPost> paramPost = paramInterface.post("POST", "");// POST,不带 id final Call<ParamPost> paramPostWithId = paramInterface.post("POST", "123");//POST ,带有 id //1.通过 "param" 接口发送 GET 请求(不带 id) paramGet.enqueue(new Callback<ParamGet>() { @Override public void onResponse(Call<ParamGet> call, Response<ParamGet> response) { try { // 得到 响应体 并输出 ParamGet paramGet1 = response.body(); System.out.println(TAG1 + paramGet1.getCode()); System.out.println(TAG1 + paramGet1.getDesc()); } catch (Exception e) { e.printStackTrace(); } Log.e("MainActivity", ""); } @Override public void onFailure(Call<ParamGet> call, Throwable t) { } }); //2.通过"param"接口发送 GET 请求,带有 id paramGetWithId.enqueue(new Callback<ParamGetWithId>() { @Override public void onResponse(Call<ParamGetWithId> call, Response<ParamGetWithId> response) { try { // 得到 响应体 并输出 ParamGetWithId paramGetId1 = response.body(); System.out.println(TAG2 + paramGetId1.getCode()); System.out.println(TAG2 + paramGetId1.getDesc()); System.out.println(TAG2 + paramGetId1.getData().getId()); } catch (Exception e) { e.printStackTrace(); } Log.e("MainActivity", ""); } @Override public void onFailure(Call<ParamGetWithId> call, Throwable t) { } }); // 3.通过 "param" 接口发送 POST 请求 ,不带 id paramPost.enqueue(new Callback<ParamPost>() { @Override public void onResponse(Call<ParamPost> call, Response<ParamPost> response) { try { // 得到 响应体 并输出 ParamPost paramPost = response.body(); System.out.println(TAG3 + paramPost.getCode()); System.out.println(TAG3 + paramPost.getDesc()); //查看返回结果,就可以发现,这行语句没有得到执行,因为 没有 id,只能得到返回失败的结果 System.out.println(TAG3 + paramPost.getData().getType()); } catch (Exception e) { e.printStackTrace(); } Log.e("MainActivity", ""); } @Override public void onFailure(Call<ParamPost> call, Throwable t) { } }); paramPostWithId.enqueue(new Callback<ParamPost>() { @Override public void onResponse(Call<ParamPost> call, Response<ParamPost> response) { try { // 得到 响应体 并输出 ParamPost paramPostWithId1 = response.body(); System.out.println(TAG4 + paramPostWithId1.getCode()); System.out.println(TAG4 + paramPostWithId1.getDesc()); System.out.println(TAG4 + paramPostWithId1.getData().getId()); System.out.println(TAG4 + paramPostWithId1.getData().getType()); } catch (Exception e) { e.printStackTrace(); } Log.e("MainActivity",""); } @Override public void onFailure(Call<ParamPost> call, Throwable t) { }); } }
运行结果如下:
最后:
Retrofit 适用于 Java 7 及 Android 2.3 以上的版本。不过现在大多数版本都是符合要求的。
作为一个初学者,我认为在学习过程中最需要的是理论+实践,理论的部分很多博客都写到了,所以我自己写博客喜欢带有案例。我认为,独立写出一个运行成功的 demo ,对于理解知识点是非常重要的。
希望这篇文章能对大家的学习有所帮助。
相关文章推荐
- (C语言)选美比赛
- CSS3与页面布局学习笔记(五)——Web Font与CSS Sprites(又称CSS精灵、雪碧图)技术
- Java外挂开发之内存修改器(类似CE)
- flume学习(四):Flume Channel Selectors使用
- 对锦标赛算法与完美洗牌的分析
- Centos 6.5下C连接MySQL测试
- 读《小王子》
- Python脚本之间调用
- Java中的Lock
- BigDecimal的使用举例,包括阶乘的相加求法思路
- android实现MIUI的时钟效果
- 网络爬虫中的Unicode码解决[实例]
- 排序lib
- Dvwa系列之csrf
- java如何输出一个对象的引用名
- R语言实战笔记--第二章 数据类型及结构
- 个人笔记
- 第十六周 项目1--验证算法(3)--冒泡排序
- 小白学《神经网络与深度学习》笔记之四-深度学习的常用方法(2)
- img标签使用绝对路径无法显示图片