Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create a REST API client with RxJava in Android

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

这篇文章主要介绍"Android中如何利用RxJava创建一个REST API客户端"的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇"Android中如何利用RxJava创建一个REST API客户端"文章能帮助大家解决问题。

添加所需的库文件开始。如果你用Maven的话,只需将下面的dependencies(依赖库)加到pom.xml中即可:

com.squareup.retrofit retrofit 1.2.2 com.netflix.rxjava rxjava-android 0.14.6

在本文中,我们将用气象地图开放平台(OpenWeatherMap) API作为演示示例。 OpenWeatherMap是一个免费的天气数据API,非常易于配置和使用,调用时只需传入位置信息(城市名或者是地理坐标)作为参数即可,具体效果请参见这个示例。它默认传输的是JSON格式的数据(但也可以配置为XML或HTML格式)。精度和温度单位也是可以配置的,更多详情请看这里。

通常要实现调用一个API需要如下这几个步骤(每个步骤都有一堆公式化代码):

创建所需的模型类(必要时,添加上注解)。

实现请求-回应管理的网络层代码,并带错误处理。

用后台线程实现请求调用(一般是用异步任务的形式实现),用一个回调函数(Callback Function)来实现在UI线程上呈现回应信息。

创建模型类

***步我们可以依靠一些类似jsonschema2pojo的JSON-POJO生成工具(半)自动化完成。OpenWeather API的模型类如下:

public class WeatherData { public Coordinates coord; public Local sys; public List weathers; public String base; public Main main; public Wind wind; public Rain rain; public Cloud clouds; public long id; public long dt; public String name; public int cod; public static class Coordinates { public double lat; public double lon; } public static class Local { public String country; public long sunrise; public long sunset; } public static class Weather { public int id; public String main; public String description; public String icon; } public static class Main { public double temp; public double pressure; public double humidity; public double temp_min; public double temp_max; public double sea_level; public double grnd_level; } public static class Wind { public double speed; public double deg; } public static class Rain { public int threehourforecast; } public static class Cloud { public int all; } }

用Retrofit实现网络调用

第二步中网络调用的实现通常我们需要写一大堆公式化的代码,但如果用Square公司的Retrofit组件来实现的话将大大减少代码量。只需要创建一个接口类(用注释来描述整个请求),然后用RestAdapter.Builder来创建客户端就行了。Retrofit也可以用来完成JSON的序列化与反序列化。

private interface ApiManagerService { @GET("/weather") WeatherData getWeather(@Query("q") String place, @Query("units") String units); }

上面的示例中我们可以看到,方法前的注释是由一个HTTP方法(我们这里用的是GET,当然你也可以按需要用Retrofit实现POST、 PUT、DELETE和HEAD方法)和一个相对路径(基本路径是由RestAdapter.Builder提供的)。@Query注释用于组装请求参 数,我们这有两个参数,一个是place(代表位置),另一个是units计量单位。

我们来看一个具体的调用示例(实际代码中应该把这个调用放到一个非UI线程里)。这段代码还是比较容易理解的:

//... final RestAdapter restAdapter = new RestAdapter.Builder() .setServer("http://api.openweathermap.org/data/2.5") .build(); final ApiManagerService apiManager = restAdapter.create(ApiManagerService.class); final WeatherData weatherData = apiManager.getWeather("Budapest,hu", "metric"); //...

怎么样,很简单吧,你只需要很少的代码就实现了整个调用过程,这就是Retrofit的威力,要了解更多,请点击这里。

用RxJava实现响应式编程

现在我们就进入第三步了:RxJava部分!我们这里示例将用它来实现异步的请求调用。但这并不是RxJava所有的功能,以下对RxJava的介绍引用自Netflix的Github 知识库:

RxJava 是一个在Java虚拟机上实现的响应式扩展库:提供了基于observable序列实现的异步调用及基于事件编程。

它扩展了观察者模式,支持数据、事件序列并允许你合并序列,无需关心底层的线程处理、同步、线程安全、并发数据结构和非阻塞I/O处理。

它支持Java5及更高版本,并支持其他一些基于JVM的语言,如Groovy、Clojure和Scala。

我们假设你已经对RxJava有一些了解。如果没有的话,强烈建议先看看这两篇 文章和Netflix在Github Wiki上的前几页。

在***的这个示例中,我们将实现一个API 管理器负责生成observable对象,并完成多并发调用(每个调用都请求同一个地址,但参数不同)。

首先我们需要将前面创建的接口类,换为这个类:

public class ApiManager { private interface ApiManagerService { @GET("/weather") WeatherData getWeather(@Query("q") String place, @Query("units") String units); } private static final RestAdapter restAdapter = new RestAdapter.Builder() .setServer("http://api.openweathermap.org/data/2.5") .build(); private static final ApiManagerService apiManager = restAdapter.create(ApiManagerService.class); public static Observable getWeatherData(final String city) { return Observable.create(new Observable.OnSubscribeFunc() { @Override public Subscription onSubscribe(Observer

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report