retrofit 学习和使用
来源:互联网 发布:万捷网络验证要多少钱 编辑:程序博客网 时间:2024/06/08 02:33
1.学习使用
(1)一般的get请求
1.1 创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()//01:获取Retrofit对象 .baseUrl("https://api.github.com")//02采用链式结构绑定Base url .addConverterFactory(GsonConverterFactory.create()) .build();//03执行操作
其中baseurl 是请求服务器地址,写到端口即可。注意要以/结束。
1.2 代理接口
GET方法 注解上面的具体的请求接口url 可以包括动态路径和参数。
public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user);// you can add some other meathod }
1.3 通过retrofit获取动态服务代理
GitHubService service = retrofit.create(GitHubService.class);//04获取API接口的实现类的实例
1.4 通过实体调用请求方法,参数,获取Call对象
Call<List<Repo>> call = service.listRepos("lengqi19860101");
private class Repo { String full_name; String forks_url; }
1.5 Call执行异步请求
call.enqueue(new Callback<List<Repo>>() { @Override public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) { List<Repo> repoList = response.body(); StringBuffer buffer = new StringBuffer(); for (Repo repo : repoList) { buffer.append(repo.full_name + ":" + repo.forks_url); } textView.setText(buffer.toString()); } @Override public void onFailure(Call<List<Repo>> call, Throwable t) { textView.setText(t.getMessage()); } });
(2)动态请求
1.动态的url访问,利用@PATH注解,例子:
public interface IUserBiz{ @GET("{username}") Call<User> getUser(@Path("username") String username);}
(2)POST请求
(3)注意点
1.接口中的方法必须有返回值,且比如是Call类型。
2.addConverterFactory(GsonConverterFactory.create())这里如果使用gson,需要额外导入:
compile ‘com.squareup.retrofit2:converter-gson:2.0.2’
当然除了gson以外,还提供了以下的选择:
Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
当然也支持自定义,你可以选择自己写转化器完成数据的转化,这个后面将具体介绍。
3.既然call.enqueue是异步的访问数据,那么同步的访问方式为call.execute,这一点非常类似okhttp的API,实际上默认情况下内部也是通过okhttp3.Call实现。
4. 动态url path 用@PATH 请求参数用 查询参数的设置@Query
5. POST请求体的方式向服务器传入json字符串@Body
http://blog.csdn.net/lmj623565791/article/details/51304204
2.原理学习
http://lib.csdn.net/article/android/54248
- retrofit 学习和使用
- Android学习和使用Retrofit框架
- Retrofit 学习使用
- Retrofit封装和使用
- 使用 RxJava 和 Retrofit
- Retrofit 和 RxJava 结合使用
- Retrofit简单介绍和使用
- Retrofit初探和简单使用
- 【Retrofit】简单介绍和使用
- Retrofit和RxJava结合使用
- RxJava和Retrofit结合使用
- RxJava和Retrofit结合使用
- Retrofit的讲解和使用
- 初次使用Retrofit和Gson
- rxjava 和retrofit 结合使用
- Retrofit、RxJava和OkHttp使用
- retrofit 使用介绍(快速了解和集成retrofit)
- Retrofit和okhttp的了解和使用
- a href=#与 a href=javascript:void(0) 的区别
- logstash grok
- Android 4.0新的广播机制FLAG_EXCLUDE_STOPPED_PACKAGES
- Codeforces 765D Artsem and Saunders 构造
- LeetCode 8. String to Integer (atoi)
- retrofit 学习和使用
- CI3框架初识-钩子
- nginx 日志配置与分割
- AndroidManifest.xml 清单文件
- Linux NTP config
- iOS设计模式-建造者模式
- android控件拖动,移动、解决父布局重绘时控件回到原点
- 任务栏窗口隐藏
- 训练2-HTML 学习H2标签