让Android应用活起来: Retrofit 和 OkHttp的比较参考

让Android应用活起来: Retrofit 和 OkHttp的比较参考

目录

前言

OkHttp

Retrofit

对比

前言

在构建现代 Android 应用时,处理网络请求是一个不可或缺的部分。其中Square 的两个开源库,Retrofit 和 OkHttp,GitHub Star数很多,被很多人选择。在我刚成为一个Android er 的时候,就对这两个库有所耳闻,不过当时果断选择了Okhttp,因为觉得更简单,现在想抽出时间探讨 Retrofit 和 OkHttp 的用法,同时对比它们的不同。

OkHttp

同步Get请求

OkHttpClient client = new OkHttpClient();

HttpUrl.Builder urlBuilder = HttpUrl.parse("url").newBuilder();

urlBuilder.addQueryParameter("a", "b");

String url = urlBuilder.build().toString();

Request request = new Request.Builder()

.url("url")

.build();

try (Response response = client.newCall(request).execute()) {

if (response.isSuccessful()) {

String responseBody = response.body().string();

} else {

}

} catch (IOException e) {

}

同步POST请求

OkHttpClient client = new OkHttpClient();

MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");

String postBody = "{\"a\": \"b\", \"c\": \"d\"}";

RequestBody body = RequestBody.create(postBody, MEDIA_TYPE);

Request request = new Request.Builder()

.url("url")

.post(body)

.build();

try (Response response = client.newCall(request).execute()) {

if (response.isSuccessful()) {

String responseBody = response.body().string();

} else {

}

} catch (IOException e) {

}

异步请求

client.newCall(request).enqueue(new Callback() {

@Override

public void onFailure(Call call, IOException e) {

}

@Override

public void onResponse(Call call, Response response) throws IOException {

if (response.isSuccessful()) {

String responseBody = response.body().string();

}

}

});

同步异步使用场景

大多数UI应用程序和需要与用户交互的场景,应该使用异步请求。

没有用户界面交互,或已经处于后台线程的场景下,可以考虑使用同步请求。

Retrofit

定义Get请求 POST请求

public interface MyApiService {

@GET("users/list")

Call> getUserList(@Query("page") int page);

@POST("users/new")

Call createUser(@Body User user);

}

Retrofit实例

Retrofit retrofit = new Retrofit.Builder()

.baseUrl("url")

.addConverterFactory(GsonConverterFactory.create())

.build();

addConverterFactory(GsonConverterFactory.create())是让Retrofit 使用 Gson 库来处理 JSON 的序列化和反序列化,Retrofit 会使用Gson将 JSON 自动转换为指定的Java类型。

创建API接口实例

MyApiService apiService = retrofit.create(MyApiService.class);

异步请求

apiService.getUserList(1).enqueue(new Callback>() {

@Override

public void onResponse(Call> call, Response> response) {

if (response.isSuccessful()) {

List users = response.body();

}

}

@Override

public void onFailure(Call> call, Throwable t) {

}

});

User newUser = new User("a", "b");

apiService.createUser(newUser).enqueue(new Callback() {

@Override

public void onResponse(Call call, Response response) {

if (response.isSuccessful()) {

User createdUser = response.body();

}

}

@Override

public void onFailure(Call call, Throwable t) {

}

});

对比

OkHttp 是更底层的网络库,专注于高效的 HTTP 通信;Retrofit 构建于 OkHttp 之上,做了一层高级的抽象。OkHttp 聚焦于网络请求的发送和响应的接收,Retrofit 则聚焦于将这些请求和响应映射到 Java 接口和类上。

笔者的其他深入Android底层文章推荐

Android源码阅读 SharedPreferences - 1-CSDN博客

Android源码阅读WorkMangaer - 1-CSDN博客

如上为两个系列。

相关文章