Square 为广大开发者奉献了OkHttp,Retrofit1.x,Retrofit2.x,运用比较广泛,这三个工具有很多相似之处,初学者可能会有一些使用迷惑。这里来总结一下它们的一些基本使用和一些细微差别。

/**************
Retrofit 基本使用方法 Retrofit 到底是返回什么? void, Observable, Call? *************/
/********************************************Retrofit****************************************************************/
/*** 同步调用的方式 ****/
interface GitHubService {
@GET("/repos/{owner}/{repo}/contributors")
List<Contributor> repoContributors(
@Path("owner") String owner,
@Path("repo") String repo);
} List<Contributor> contributors =
gitHubService.repoContributors("square", "retrofit");
/***** 异步调用的方式 仅限于 Retrofit 1.x !!!!!!! *****/
interface GitHubService {
@GET("/repos/{owner}/{repo}/contributors")
void repoContributors(
@Path("owner") String owner,
@Path("repo") String repo,
Callback<List<Contributor>> cb); // 异步调用添加 CallBack
} service.repoContributors("square", "retrofit", new Callback<List<Contributor>>() {
@Override void success(List<Contributor> contributors, Response response) {
// ...
} @Override void failure(RetrofitError error) {
// ...
}
}); /**** Rxjava 方式 ****/
interface GitHubService {
@GET("/repos/{owner}/{repo}/contributors")
Observable<List<Contributor>> repoContributors(
@Path("owner") String owner,
@Path("repo") String repo);
}
// 调用
gitHubService.repoContributors("square", "retrofit")
.subscribe(new Action1<List<Contributor>>() {
@Override public void call(List<Contributor> contributors) {
// ...
}
}); /*******************************注意以下三个Callback的不同***************************************/ // Retrofit Callback Version 1.9
public interface Callback<T> { /** Successful HTTP response. */
void success(T t, Response response); /**
* Unsuccessful HTTP response due to network failure, non-2XX status code, or unexpected
* exception.
*/
void failure(RetrofitError error);
}
// Retrofit Callback Version 2.0 !!!!!!!!!
public interface Callback<T> {
/** Successful HTTP response. */
void onResponse(Response<T> response, Retrofit retrofit); /** Invoked when a network or unexpected exception occurred during the HTTP request. */
void onFailure(Throwable t);
}
// OkHttp
public interface Callback {
  void onFailure(Request request, IOException e);   void onResponse(Response response) throws IOException; // 注意参数不同
} /*********************************回顾一下Okhttp的调用方式********************************************/ //1. 创建
OkHttpClient : OkHttpClient client = new OkHttpClient();
//2. 创建
Request : Request request = new Request.Builder()
.url("https://api.github.com/repos/square/okhttp/issues")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Accept", "application/json; q=0.5")
.addHeader("Accept", "application/vnd.github.v3+json")
.build(); //3. 使用 client 执行请求(两种方式):
//第一种,同步执行
Response response = client.newCall(request).execute();
// 第二种,异步执行方式
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, Throwable throwable) {
// 复写该方法 }
@Override public void onResponse(Response response) throws IOException {
// 复写该方法
}
} /***********************************Retrofit 1.0 不能获得 Header 或者整个 Body*****************************************/
/**********2.x 引入 Call , 每个Call只能调用一次,可以使用Clone方法来生成一次调用多次,使用Call既可以同步也可以异步*********/ interface GitHubService {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> repoContributors(
@Path("owner") String owner,
@Path("repo") String repo);
} Call<List<Contributor>> call =
gitHubService.repoContributors("square", "retrofit"); response = call.execute(); /*************** 同步的方式调用,注意这里返回了 Response 后面会提到 ********************/ // This will throw IllegalStateException: 每个Call只能执行一次
response = call.execute(); Call<List<Contributor>> call2 = call.clone(); // 调用Clone之后又可以执行
// This will not throw:
response = call2.execute(); /************************ 异步的方式调用 *********************************/ Call<List<Contributor>> call =
gitHubService.repoContributors("square", "retrofit"); call.enqueue(new Callback<List<Contributor>>() {
@Override void onResponse(/* ... */) {
// ...
} @Override void onFailure(Throwable t) {
// ...
}
}); /****************************引入 Response,获取返回的RawData,包括:response code, response message, headers**********************************/ class Response<T> {
int code();
String message();
Headers headers(); boolean isSuccess();
T body();
ResponseBody errorBody();
com.squareup.okhttp.Response raw();
} interface GitHubService {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> repoContributors(
@Path("owner") String owner,
@Path("repo") String repo);
} Call<List<Contributor>> call =
gitHubService.repoContributors("square", "retrofit");
Response<List<Contributor>> response = call.execute(); /*********************************** Dynamic URL *****************************************/ interface GitHubService {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> repoContributors(
@Path("owner") String owner,
@Path("repo") String repo); @GET
Call<List<Contributor>> repoContributorsPaginate(
@Url String url);// 直接填入 URL 而不是在GET中替换字段的方式
} /*************************************根据返回值实现重载*****************************************************/
interface SomeService {
@GET("/some/proto/endpoint")
Call<SomeProtoResponse> someProtoEndpoint(); // SomeProtoResponse @GET("/some/json/endpoint")
Call<SomeJsonResponse> someJsonEndpoint(); // SomeJsonResponse
} interface GitHubService {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> repoContributors(..); @GET("/repos/{owner}/{repo}/contributors")
Observable<List<Contributor>> repoContributors2(..); @GET("/repos/{owner}/{repo}/contributors")
Future<List<Contributor>> repoContributors3(..); // 可以返回 Future
} /******************************************Retrofit 1.x Interceptor,添加头部信息的时候经常用到Interceptor*************************************************************/
RestAdapter.Builder builder = new RestAdapter.Builder().setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json;versions=1");
}
}); /******************************************Retrofit 2.x Interceptor**************************************************/ OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request(); Request request = original.newBuilder()
.header("Accept", "application/json")
.header("Authorization", "auth-token")
.method(original.method(), original.body())
.build(); Response response = chain.proceed(request);
return response; }
} Retrofit retrofit = Retrofit.Builder()
.baseUrl("https://your.api.url/v2/")
.client(client).build(); /***************************************异步实例*********************************************/
public interface APIService { @GET("/users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user); @GET("/users/{user}/repos")
Call<String> listReposStr(@Path("user") String user);
//错误,不能这样使用异步
// @GET("/users/{user}/repos")
// void listRepos(@Path("user") String user, Callback<List<Repo>> callback);
} private void prepareServiceAPI() {
//For logging
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient();
client.interceptors().add(new MyInterceptor());
client.interceptors().add(logging);
// setUp Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
//.addConverterFactory(new ToStringConverterFactory())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build(); service = retrofit.create(APIService.class);
}
// 异步调用
public void execute() {
Call<List<Repo>> call = service.listRepos("pasha656");
call.enqueue(new Callback<List<Repo>>() {
@Override
public void onResponse(Response<List<Repo>> response, Retrofit retrofit) { if (response.isSuccess()) {
if (!response.body().isEmpty()) {
StringBuilder sb = new StringBuilder();
for (Repo r : response.body()) {
sb.append(r.getId()).append(" ").append(r.getName()).append(" \n");
}
activity.setText(sb.toString());
}
} else {
APIError error = ErrorUtils.parseError(response, retrofit);
Log.d("Pasha", "No succsess message "+error.getMessage());
} if (response.errorBody() != null) {
try {
Log.d("Pasha", "Error "+response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}
} @Override
public void onFailure(Throwable t) {
Log.d("Pasha", "onFailure "+t.getMessage());
}
});
}

  

OkHttp,Retrofit 1.x - 2.x 基本使用的更多相关文章

  1. Android开发okhttp,retrofit,android-async-http,volley?

    okhttp, retrofit,android-async-http,volley这四个框架适用的场合?优缺点?各位大大,请给一些建议.我准备开发一个新的APP 如果是标准的RESTful API, ...

  2. 一行代码实现Okhttp,Retrofit,Glide下载上传进度监听

    https://mp.weixin.qq.com/s/bopDUFMB7EiK-MhLc3KDXQ essyan 鸿洋 2017-06-29 本文作者 本文由jessyan投稿. jessyan的博客 ...

  3. Android OkHttp + Retrofit 断点续传

    本文链接 前面我们已经知道如何使用OkHttp+Retrofit下载文件. 下载文件时,可能会遇到一些意外情况,比如网络错误或是用户暂停了下载. 再次启动下载,如果又要从头开始,会白白浪费前面下载好的 ...

  4. Android 框架学习之 第一天 okhttp & Retrofit

    最近面试,一直被问道新技术新框架,这块是短板,慢慢补吧. 关于框架的学习,分几个步骤 I.框架的使用 II.框架主流使用的版本和Android对应的版本 III.框架的衍生使用比如okhttp就会有R ...

  5. Android OkHttp + Retrofit 取消请求的方法

    本文链接 前言 在某一个界面,用户发起了一个网络请求,因为某种原因用户在网络请求完成前离开了当前界面,比较好的做法是取消这个网络请求.对于OkHttp来说,具体是调用Call的cancel方法. 如何 ...

  6. Android OkHttp + Retrofit 下载文件与进度监听

    本文链接 下载文件是一个比较常见的需求.给定一个url,我们可以使用URLConnection下载文件. 使用OkHttp也可以通过流来下载文件. 给OkHttp中添加拦截器,即可实现下载进度的监听功 ...

  7. Android 使用Okhttp/Retrofit持久化cookie的简便方式

    首先cookie是什么就不多说了,还是不知道的话推荐看看这篇文章 Cookie/Session机制详解 深入解析Cookie技术 为什么要持久化cookie也不多说了,你能看到这篇文章代表你有这个需求 ...

  8. 高仿Android网易云音乐OkHttp+Retrofit+RxJava+Glide+MVC+MVVM

    简介 这是一个使用Java(以后还会推出Kotlin版本)语言,从0开发一个Android平台,接近企业级的项目(我的云音乐),包含了基础内容,高级内容,项目封装,项目重构等知识:主要是使用系统功能, ...

  9. [Android] 转-RxJava+MVP+Retrofit+Dagger2+Okhttp大杂烩

    原文url: http://blog.iliyun.net/2016/11/20/%E6%A1%86%E6%9E%B6%E5%B0%81%E8%A3%85/ 这几年来android的网络请求技术层出不 ...

随机推荐

  1. hdu2604(递推,矩阵快速幂)

    题目链接:hdu2604 这题重要的递推公式,找到公式就很easy了(这道题和hdu1757(题解)类似,只是这道题需要自己推公式) 可以直接找规律,推出递推公式,也有另一种找递推公式的方法:(PS: ...

  2. nginx.conf各参数的意义

    搬运+翻译至 http://qiita.com/syou007/items/3e2d410bbe65a364b603 /etc/nginx/nginx.conf 记录各个参数的意义 user user ...

  3. Android热修复技术选型(不在市场发布新版本的情况下,直接更新app)

    2015年以来,Android开发领域里对热修复技术的讨论和分享越来越多,同时也出现了一些不同的解决方案,如QQ空间补丁方案.阿里AndFix以及微信Tinker,它们在原理各有不同,适用场景各异,到 ...

  4. 微软connect教程系列—EntityFramework7(三)

      随着Asp.NET5的开源,以及跨平台,ORM框架EF7也与时俱进,支持asp.net core,也支持关系型数据库和非关系型数据库,以及在linux和mac上跨平台使用. 下面演示的即通过使用E ...

  5. 【腾讯bugly干货】QQ空间直播秒开优化实践

    本文来自于腾讯bugly开发者社区,非经作者同意,请勿转载,原文地址为:http://bugly.qq.com/bbs/forum.php?mod=viewthread&tid=1204&am ...

  6. PostgreSQL基础整理(二)

    存储过程 实现功能:针对工资表30岁以下,工资提升10% 30至40提升20% 40以上提升30% + 奖金(入参)返回平均薪酬 创建表: DROP TABLE emps; CREATE TABLE ...

  7. 关于RPC与MQ异同的理解

    最近看了一些资料,回顾过去项目的经验,梳理自己对两者异同的理解: 相同: 1.都利于大型系统的解耦: 2.都提供子系统之间的交互,特别是异构子系统(如java\node等不同开发语言): 不同: 1. ...

  8. 通过Measure & Arrange实现UWP瀑布流布局

    简介 在以XAML为主的控件布局体系中,有用于完成布局的核心步骤,分别是measure和arrange.继承体系中由UIElement类提供Measure和Arrange方法,并由其子类Framewo ...

  9. Spring中Ordered接口简介

    目录 前言 Ordered接口介绍 Ordered接口在Spring中的使用 总结 前言 Spring中提供了一个Ordered接口.Ordered接口,顾名思义,就是用来排序的. Spring是一个 ...

  10. Angular ngClick 阻止冒泡和默认行为

    这其实是一个很简单的问题,如果你认真查看过Angular官方的API文档,本来不想记录的.但是这个问题不止一次的被人问起,所以今天在记录在这里. 在Angular中已经对一些ng事件如ngClick, ...