Retrofit的初步使用
来源:互联网 发布:linux组织文件目录结构 编辑:程序博客网 时间:2024/04/19 21:24
纪录下Retrofit的初步使用笔记。Retrofit用的还是okhttp,不过做了进一步的拓展,调用起来比单纯的使用okhttp方便多了(先理解)。
文章以解析https://api.github.com/users/Jayden37 为例子。
Retrofit官网地址http://square.github.io/retrofit/
首先,在清单文件中加上网络的权限<uses-permission android:name="android.permission.INTERNET" />,然后在主模块的build.gradle配置上依赖,用的是2.1.0的版本,以官网最新的版本为准。
compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0'下一步,定义一个接口,用的是注解的方式,@Get代表的是get请求方式,/users/{user}是请求地址的拼接字符,后面配置的时候会配置上基址https://api.github.com。{user}是占位符,后面调用的时候会传值过来,如传字符串“Jayden37”。方法repo是自己取的名字,@Path代表拼接的字符,就是传过来的字符取代{user}占位符的位置。repo方法会返回一个Call的对象。
public interface APIInterface { /**https://api.github.com/users/Jayden37*/ @GET("/users/{user}") Call<TestModel> repo(@Path("user") String user);}TestModel对应的是https://api.github.com/users/Jayden37 返回的gson解析后的Bean对象。这里没有写完整。只写了第一个值。
public class TestModel { private String login; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public TestModel(String login) { this.login = login; }}然后在MainActivity调用Retrofit的方法。先获取Retrofit对象,baseUrl配置的就是基址,会拼接你的请求前面,如APIInterface的@Get("users/{user}"),拼接后就是https://api.github.com/users/{user},addConverterFactory是Gson解析用到的。 调用retrofit.create获取到接口对象apiInterface,apiInterface调用方法repo(Jayden37)传入占位符的值,所以接口{user}替代为Jayden37,地址变为https://api.github.com/users/Jayden37 ,返回Call对象modelCall,modelCall执行enqueue异步操作,会回调到主线程onResponse、onFailure成功和失败两个方法。
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create()) .build(); APIInterface apiInterface = retrofit.create(APIInterface.class); Call<TestModel> modelCall = apiInterface.repo("Jayden37"); modelCall.enqueue(new Callback<TestModel>() { @Override public void onResponse(Call<TestModel> call, Response<TestModel> response) { Log.i(TAG,response.body().getLogin()); } @Override public void onFailure(Call<TestModel> call, Throwable t) { Log.e(TAG,"请求失败="+t.getMessage()+":"+t.toString()); } });
打印的结果为:jayden37代表请求
成功。
项目地址:https://github.com/37Jayden/RetrofitDemo
0 0
- Retrofit的初步使用
- Retrofit 初步的使用
- Mvp-Retrofit-Rxjava-Rxbus的初步使用
- Android之retrofit初步使用
- Retrofit结合Rxjava初步使用
- 对于Retrofit的初步学习
- Retrofit 的使用
- retrofit 的使用。
- Retrofit 的使用简介
- Retrofit的使用封装
- retrofit的使用
- Retrofit的简单使用
- retrofit的使用
- Retrofit的简单使用
- Retrofit的简单使用
- Retrofit + RxAndroid的使用
- Retrofit框架的使用
- Retrofit+RxJava的使用
- java使用url读取网页资源
- 仿美团首页功能选择的实现
- iostream流库
- hdu 2642 stars
- AIDL详解
- Retrofit的初步使用
- 【c++】构建一棵简单的二叉树
- 蓝牙之十六-测试认证
- UVa 227 Puzzle(谜题)
- Java实现快速,选择,希尔,归并排序算法
- LeetCode 199.Binary Tree Right Side View
- web文章收录
- 【转载】C#操作Access类
- 新建webservice项目时,在target runtime中找不到apache(已经安装过了),只有basic