Android开发网络通信一开始的时候使用的是AsyncTask封装HttpClient,没有使用原生的HttpURLConnection就跳到了Volley,随着OkHttp的流行又开始迁移到OkHttp上面,随着Rxjava的流行又了解了Retrofit,随着Retrofit的发展又从1.x到了2.x......。好吧,暂时到这里。

  那么的多的使用工具有时候有点眼花缭乱,今天来总结一下现在比较流行的基于OkHttp 和 Retrofit 的网络通信API设计方法。有些同学可能要想,既然都有那么好用的Volley和Okhttp了,在需要用到的地方创建一个Request然后交给RequestQueue(Volley的方式)或者 Call(Okhttp的方式)就行了吗,为什么还那么麻烦? 但是我认为这种野生的网络库的用法还是是有很多弊端(弊端就不说了,毕竟是总结新东西),在好的Android架构中都不会出现这样的代码。

  网络通信都是异步完成,设计网络API我觉得首先需要考虑异步结果的返回机制。基于Okhttp或Retrofit,我们考虑如何返回异步的返回结果,有几种方式:

  1. 直接返回:

  OkHttp 的返回方式:

OkHttpClient : OkHttpClient client = new OkHttpClient();

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(); //第一种
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 的方式:

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();

  上面的方式适用于野生的返回网络请求的内容。

  2. 使用事件总线(Otto,EventBus,RxBus(自己使用PublishSubject封装))

  代码来源:https://github.com/saulmm/Material-Movies

public interface MovieDatabaseAPI { /************Retrofit 1.x ,使用异步的方式返回 ****************/

    @GET("/movie/popular")
void getPopularMovies(
@Query("api_key") String apiKey,
Callback<MoviesWrapper> callback); @GET("/movie/{id}")
void getMovieDetail (
@Query("api_key") String apiKey,
@Path("id") String id,
Callback<MovieDetail> callback
); @GET("/movie/popular")
void getPopularMoviesByPage(
@Query("api_key") String apiKey,
@Query("page") String page,
Callback<MoviesWrapper> callback
); @GET("/configuration")
void getConfiguration (
@Query("api_key") String apiKey,
Callback<ConfigurationResponse> response
); @GET("/movie/{id}/reviews")
void getReviews (
@Query("api_key") String apiKey,
@Path("id") String id,
Callback<ReviewsWrapper> response
); @GET("/movie/{id}/images")
void getImages (
@Query("api_key") String apiKey,
@Path("id") String movieId,
Callback<ImagesWrapper> response
);
}

  

public class RestMovieSource implements RestDataSource {

    private final MovieDatabaseAPI moviesDBApi;
private final Bus bus; /***********使用了Otto**************/ public RestMovieSource(Bus bus) { RestAdapter movieAPIRest = new RestAdapter.Builder() /*** Retrofit 1.x ***/
.setEndpoint(Constants.MOVIE_DB_HOST)
.setLogLevel(RestAdapter.LogLevel.HEADERS_AND_ARGS)
.build(); moviesDBApi = movieAPIRest.create(MovieDatabaseAPI.class);
this.bus = bus;
} @Override
public void getMovies() { moviesDBApi.getPopularMovies(Constants.API_KEY, retrofitCallback);
} @Override
public void getDetailMovie(String id) { moviesDBApi.getMovieDetail(Constants.API_KEY, id,
retrofitCallback);
} @Override
public void getReviews(String id) { moviesDBApi.getReviews(Constants.API_KEY, id,
retrofitCallback);
} @Override
public void getConfiguration() { moviesDBApi.getConfiguration(Constants.API_KEY, retrofitCallback);
} @Override
public void getImages(String movieId) { moviesDBApi.getImages(Constants.API_KEY, movieId,
retrofitCallback);
} public Callback retrofitCallback = new Callback() { /******************这里统一的Callback,根据不同的返回值使用事件总线进行返回**************************/
@Override
public void success(Object o, Response response) { if (o instanceof MovieDetail) { MovieDetail detailResponse = (MovieDetail) o;
bus.post(detailResponse); } else if (o instanceof MoviesWrapper) { MoviesWrapper moviesApiResponse = (MoviesWrapper) o;
bus.post(moviesApiResponse); } else if (o instanceof ConfigurationResponse) { ConfigurationResponse configurationResponse = (ConfigurationResponse) o;
bus.post(configurationResponse); } else if (o instanceof ReviewsWrapper) { ReviewsWrapper reviewsWrapper = (ReviewsWrapper) o;
bus.post(reviewsWrapper); } else if (o instanceof ImagesWrapper) { ImagesWrapper imagesWrapper = (ImagesWrapper) o;
bus.post(imagesWrapper);
}
} @Override
public void failure(RetrofitError error) { System.out.printf("[DEBUG] RestMovieSource failure - " + error.getMessage());
}
}; @Override
public void getMoviesByPage(int page) { moviesDBApi.getPopularMoviesByPage(
Constants.API_KEY,
page + "",
retrofitCallback
);
}
}

  

  3. 返回Observable(这里也可以考虑直接返回Observable 和间接返回Observable)

  直接的返回 Observable,在创建 apiService 的时候使用 Retrofit.create(MovieDatabaseAPI)就行了(见下面代码)

public interface MovieDatabaseAPI {

    @GET("/movie/popular")
Observable<MovieWrapper> getPopularMovies(
@Query("api_key") String apiKey,
); @GET("/movie/{id}")
Observable<MovideDetail> getMovieDetail (
@Query("api_key") String apiKey,
@Path("id") String id,
);
}  

  间接返回Observable,这里参考了AndroidCleanArchitecture:

public interface RestApi {   /************定义API接口*****************/
String API_BASE_URL = "http://www.android10.org/myapi/"; /** Api url for getting all users */
String API_URL_GET_USER_LIST = API_BASE_URL + "users.json";
/** Api url for getting a user profile: Remember to concatenate id + 'json' */
String API_URL_GET_USER_DETAILS = API_BASE_URL + "user_"; /**
* Retrieves an {@link rx.Observable} which will emit a List of {@link UserEntity}.
*/
Observable<List<UserEntity>> userEntityList(); /**
* Retrieves an {@link rx.Observable} which will emit a {@link UserEntity}.
*
* @param userId The user id used to get user data.
*/
Observable<UserEntity> userEntityById(final int userId);
}

  

/**** 使用Rx Observable 实现 RestApi 接口,实际调用的是 ApiConnection 里面的方法  ****/
public class RestApiImpl implements RestApi { /***注意这里没有使用Retrofit,而是对上面接口的实现***/ private final Context context;
private final UserEntityJsonMapper userEntityJsonMapper; /**
* Constructor of the class
*
* @param context {@link android.content.Context}.
* @param userEntityJsonMapper {@link UserEntityJsonMapper}.
*/
public RestApiImpl(Context context, UserEntityJsonMapper userEntityJsonMapper) {
if (context == null || userEntityJsonMapper == null) {
throw new IllegalArgumentException("The constructor parameters cannot be null!!!");
}
this.context = context.getApplicationContext();
this.userEntityJsonMapper = userEntityJsonMapper;
} @RxLogObservable(SCHEDULERS)
@Override
public Observable<List<UserEntity>> userEntityList() {
return Observable.create(subscriber -> {
if (isThereInternetConnection()) {
try {
String responseUserEntities = getUserEntitiesFromApi();
if (responseUserEntities != null) {
subscriber.onNext(userEntityJsonMapper.transformUserEntityCollection(
responseUserEntities));
subscriber.onCompleted();
} else {
subscriber.onError(new NetworkConnectionException());
}
} catch (Exception e) {
subscriber.onError(new NetworkConnectionException(e.getCause()));
}
} else {
subscriber.onError(new NetworkConnectionException());
}
});
} @RxLogObservable(SCHEDULERS)
@Override
public Observable<UserEntity> userEntityById(final int userId) {
return Observable.create(subscriber -> {
if (isThereInternetConnection()) {
try {
String responseUserDetails = getUserDetailsFromApi(userId);
if (responseUserDetails != null) {
subscriber.onNext(userEntityJsonMapper.transformUserEntity(responseUserDetails));
subscriber.onCompleted();
} else {
subscriber.onError(new NetworkConnectionException());
}
} catch (Exception e) {
subscriber.onError(new NetworkConnectionException(e.getCause()));
}
} else {
subscriber.onError(new NetworkConnectionException());
}
});
} private String getUserEntitiesFromApi() throws MalformedURLException {
return ApiConnection.createGET(RestApi.API_URL_GET_USER_LIST).requestSyncCall();
} private String getUserDetailsFromApi(int userId) throws MalformedURLException {
String apiUrl = RestApi.API_URL_GET_USER_DETAILS + userId + ".json";
return ApiConnection.createGET(apiUrl).requestSyncCall();
} /**
* Checks if the device has any active internet connection.
*
* @return true device with internet connection, otherwise false.
*/
private boolean isThereInternetConnection() {
boolean isConnected; ConnectivityManager connectivityManager =
(ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
isConnected = (networkInfo != null && networkInfo.isConnectedOrConnecting()); return isConnected;
}
}

  

public class ApiConnection implements Callable<String> {  /***********************网络接口的实际实现********************************/

    private static final String CONTENT_TYPE_LABEL = "Content-Type";
private static final String CONTENT_TYPE_VALUE_JSON = "application/json; charset=utf-8"; private URL url;
private String response; private ApiConnection(String url) throws MalformedURLException {
this.url = new URL(url);
} public static ApiConnection createGET(String url) throws MalformedURLException {
return new ApiConnection(url);
} /**
* Do a request to an api synchronously.
* It should not be executed in the main thread of the application.
*
* @return A string response
*/
@Nullable
public String requestSyncCall() {
connectToApi();
return response;
} private void connectToApi() {
OkHttpClient okHttpClient = this.createClient(); /*******************使用OKhttp的实现*******************/
final Request request = new Request.Builder()
.url(this.url)
.addHeader(CONTENT_TYPE_LABEL, CONTENT_TYPE_VALUE_JSON)
.get()
.build(); try {
this.response = okHttpClient.newCall(request).execute().body().string();
} catch (IOException e) {
e.printStackTrace();
}
} private OkHttpClient createClient() {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(10000, TimeUnit.MILLISECONDS);
okHttpClient.setConnectTimeout(15000, TimeUnit.MILLISECONDS); return okHttpClient;
} @Override
public String call() throws Exception {
return requestSyncCall();
}
}

  这里简单总结了一下OkHttp和Retrofit该如何封装,这样的封装放在整个大的代码框架中具有很好的模块化效果。对于使用MVP架构或者类似架构的APP,良好的网络接口模块封装是非常重要的。

Android 网络通信API的选择和实现实例的更多相关文章

  1. 【NFC】Android NFC API Reference中英文

    0 Near Field Communication Near Field Communication (NFC) is a set of   short-range wireless technol ...

  2. Android网络通信(8):WiFi Direct

    Android网络通信之WiFi Direct 使用Wi-Fi Direct技术可以让具备硬件支持的设备在没有中间接入点的情况下进行直接互联.Android 4.0(API版本14)及以后的系统都提供 ...

  3. Android网络通信(7):NFC

    Android网络通信之 NFC NFC:近场通信,是一种超近距离的无线通信技术.Android从2.3版本的SDK开始支持基于NFC通信.基于NFC的识别和通信可分为三个步骤:1.Android通过 ...

  4. 地图API的选择和使用

    在我们程序员的日常开发中,总会时不时的需要用到地图开发,我也在多次碰到之后,写下我对地图开发的理解经验和总结. 一.地图的选择 回想一下我们生活中用到的地图工具,数了一下,百度地图,高德地图,腾讯地图 ...

  5. Android开发-API指南-<activity>

    <activity> 英文原文:http://developer.android.com/guide/topics/manifest/activity-element.html 采集(更新 ...

  6. Android N API预览

    Android N for Developers 重要的开发人员功能 多窗体支持 通知 JIT/AOT 编译 高速的应用安装路径 外出瞌睡模式 后台优化 Data Saver 高速设置图块 API 号 ...

  7. Android经典项目开发之天气APP实例分享

    原文:Android经典项目开发之天气APP实例分享 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/mzc186/article/details/5 ...

  8. [转载]android网络通信解析

    原文地址:android网络通信解析作者:clunyes 网络编程的目的就是直接戒间接地通过网络协议不其他计算机进行通讯. 网络编程中有两个主要的问题, 一个是如何准确的定位网络上一台戒多台指主机: ...

  9. Android 从图库到选择图片onActivityResult接收注意的问题

    从图库选择图片然后返回数据接收处理的时候,这个时候我们可能会遇到一个问题.就是明明我走了返回的代码.但是为什么我的图片路径没有拿到?这个时候可能是Android的api不同导致,因为Android4. ...

随机推荐

  1. 0002--Weekly Meeting on 27th March and 3th April, 2015

    27th March, 2015 (1) RankNet && PageRank ->reporter: jinquan Du   Web_RankNet  Web_PageRa ...

  2. zookeeper 简介

    一.简介 zookeeper是hadoop的一个子项目,A distribute coordination service for distributed applications 为了分布式应用而开 ...

  3. 调试SQLSERVER (三)使用Windbg调试SQLSERVER的一些命令

    调试SQLSERVER (三)使用Windbg调试SQLSERVER的一些命令 调试SQLSERVER (一)生成dump文件的方法调试SQLSERVER (二)使用Windbg调试SQLSERVER ...

  4. Amazon AWS EC2开启Web服务器配置

    在Amazon AWS EC2申请了一年的免费使用权,安装了CentOS + Mono + Jexus环境做一个Web Server使用. 在上述系统安装好之后,把TCP 80端口开启(iptable ...

  5. WebAdaptor Object reference not set to an instance of an object.

    C:\inetpub\wwwroot\arcgis目录下webAdaptor.config文件内容被清空,从别的地方拷贝一份即可. <?xml version="1.0" e ...

  6. http学习笔记(四)——HTTP报文

    http报文是在http应用程序之间发送的数据块,这些数据块以一些文本形式的元信息. 请求报文从客户端流入服务器,向服务器请求数据,服务器响应请求,响应报文从服务器流出,回到客户端. 这就构成了一个事 ...

  7. SharePoint—用REST方式访问列表

    REST的定义与作用 在SharePoint 2010中,基本上有如下几种数据访问方式: 服务器端对象模型 LINQ to SharePoint Web Service 客户端对象模型 ADO.NET ...

  8. MySQL模糊查询(like)时区分大小写

    问题说明:通过上面的语句,你会发现MySQL的like查询是不区分大小写的,因为我的失误,把Joe写成了joe才发现了这个东东吧.但是,有时候,我们需要区分大小写的是,该怎么办呢?解决方法如下: 方法 ...

  9. Linux grep总结(转)

    源自:http://www.cnblogs.com/end/archive/2012/02/21/2360965.html 1.作用Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表 ...

  10. multiOTP配置安装

    https://code.google.com/p/google-authenticator/ 是google提供的OTP解决方案. http://www.multiotp.net/ 是一个开源otp ...