博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
retrofit2.6.0_RxAndroid和Retrofit 2.0
阅读量:2536 次
发布时间:2019-05-11

本文共 8407 字,大约阅读时间需要 28 分钟。

retrofit2.6.0

by Ahmed Rizwan

通过艾哈迈德·里兹万(Ahmed Rizwan)

RxAndroid和Retrofit 2.0 (RxAndroid and Retrofit 2.0)

Ok, so this isn’t new or anything, but I thought let’s just make a simple tutorial with the new Retrofit 2.0. This should give us a starting point.

好的,这不是什么新鲜事物,但我想让我们使用新的Retrofit 2.0进行简单的教程即可。 这应该给我们一个起点。

This isn’t a tutorial for RxAndroid. If you don’t know much about RxAndroid, you should first check out.

这不是RxAndroid的教程。 如果你没有太多关于RxAndroid知道,你应该首先检查出来。

Let’s get into it then. Here are the things you’ll need before we start:

让我们开始吧。 在开始之前,您需要满足以下条件:

  1. and

  2. (I’ll be using Gson, you can use other parsers as well)

    (我将使用Gson,您也可以使用其他解析器)

  3. An Internet connection!

    互联网连接!

So after you’ve added the dependencies, your gradle files should look something like this (ignore the plugin, I just added it for code conciseness because… Lambdas! *_*):

因此,在添加依赖项之后,您的gradle文件应如下所示(忽略插件,我只是为了代码简洁而添加了它,因为……Lambdas!* _ *):

Now you might be wondering, what is Retrofit exactly? Well, Retrofit is an HTTP Client, but it’s type-safe. That means you can transform an HTTP API into a Java Interface. This makes it ridiculously convenient to interact with the API.

现在您可能想知道,Retrofit到底是什么? 好吧,Retrofit是一个HTTP客户端,但是它是类型安全的。 这意味着您可以将HTTP API转换为Java接口。 这使得与API交互非常方便。

起始示例 (The Starting Example)

In the example, I’m going to use the and I’ll keep it as simple as possible. I’ll just get the in three steps.

在示例中,我将使用 ,并将使其尽可能简单。 我将通过三个步骤的 。

步骤1:从JSON生成Java模型(Pojo)类 (Step 1: Generate Java Model (Pojo) classes from JSON)

Here’s the API URL:

这是API URL:

http://api.openweathermap.org/data/2.5/weather?q=London

And the response returned when you call it is:

调用时返回的响应是:

{ “coord”: { “lon”: -0.13, “lat”: 51.51 }, “weather”: [ { “id”: 521, “main”: “Rain”, “description”: “shower rain”, “icon”: “09d” } ], “base”: “cmc stations”, “main”: { “temp”: 289.49, “pressure”: 993, “humidity”: 67, “temp_min”: 285.93, “temp_max”: 291.15 }, “wind”: { “speed”: 8.7, “deg”: 210, “gust”: 14.4 }, “rain”: { “1h”: 1.02 }, “clouds”: { “all”: 40 }, “dt”: 1442242382, “sys”: { “type”: 1, “id”: 5091, “message”: 0.0052, “country”: “GB”, “sunrise”: 1442208848, “sunset”: 1442254609 }, “id”: 2643743, “name”: “London”, “cod”: 200}

Looks pretty messy, right? Well, don’t worry, just go to this awesome and paste in the JSON. It’ll come out looking like this:

看起来很乱,对吗? 好吧,不用担心,只需转到这个很棒的并粘贴JSON。 它看起来像这样:

If the JSON has to many model classes to be generated, the easier thing to do is generate a Jar and download it, extract it, and then add the files. Otherwise just click on Preview, and copy-paste the classes you need. Do remove the @Generated(“org.jsonschema2pojo”) from each model class, as this annotation isn’t recognized by Android by default.

如果JSON必须要生成许多模型类,则更简单的方法是生成一个Jar并下载,解压缩然后添加文件。 否则,只需单击“预览”,然后复制粘贴所需的类。 请从每个模型类中删除@Generated(“ org.jsonschema2pojo”) 因为默认情况下Android无法识别此注释。

I downloaded the Jar because there are a lot of classes. And also because I’m lazy. :)

我下载了Jar,因为有很多课程。 而且还因为我很懒。 :)

After extracting and adding the classes, now the project tree looks something like this:

提取并添加了类之后,现在项目树如下所示:

So far, so good!

到目前为止,一切都很好!

步骤2:为您的API调用创建改造接口 (Step 2: Create Retrofit Interface for your API calls)

For Retrofit, you have to create an interface for the endpoints of your API.

对于Retrofit,您必须为API的端点创建一个接口。

When creating the interface, you should ask yourself: what exactly is the meaning of life? And secondly: what information do I need from the API?

创建界面时,您应该问自己:生命的确切含义是什么? 其次:API需要什么信息?

For me, the answer to both questions is WeatherData (the top-most object). Now let’s examine the URL:

对我来说,这两个问题的答案都是WeatherData(最上面的对象)。 现在让我们检查URL:

http://api.openweathermap.org/data/2.5/weather?q=London

There’s a query at the very end, so I’ll do this:

最后有一个查询 ,所以我要这样做:

Note: in Retrofit 2.0, the endpoint path string should NOT start with “/”
@GET("/weather?") --> incorrect@GET("weather?")  --> correct

Now as parameter, I’ll send the query value using the @Query annotation.

现在作为参数,我将使用@Query批注发送查询值。

As you’ll notice, I’m returning the Observable of WeatherData. That’s Rx right there!

您会注意到,我正在返回WeatherData的Observable 。 那就是Rx!

步骤3:创建Retrofit Adapter和WeatherService实例 (Step 3: Create the Retrofit Adapter and WeatherService instance)

Now in our Activity, we have to create a Retrofit adapter using the Base URL, along with some other info. Once built, we can initiate an object of WeatherService interface, then call the method.

现在,在我们的活动中,我们必须使用基本URL以及一些其他信息来创建改造适配器。 构建完成后,我们可以启动WeatherService接口的对象,然后调用该方法。

Take a look at this delicious code:

看一下这个美味的代码:

So the question here is what the hell are those addCallAdapter and addConverterFactory methods doing there?

所以这里的问题是,那些addCallAdapteraddConverterFactory方法到底在做什么?

Well in order for our calls to return type Observable, we have to set the call adapter to RxJavaCallAdapter.

为了使我们的调用返回Observable类型,我们必须将调用适配器设置为RxJavaCallAdapter

And addConverFactory is there to tell Retrofit which sort of converter I want it to use for serializing the JSON. I prefer the GSON converter. There are other converters available too.

addConverFactory可以告诉Retrofit我希望它用于序列化JSON的转换器。 我更喜欢GSON转换器。 也有其他转换器可用。

So, for these two you need to add their dependencies to your gradle:

因此,对于这两个,您需要将它们的依赖项添加到gradle中:

compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'compile 'com.squareup.retrofit2:converter-gson:2.0.0'

Now run the code, and voila! It’ll log the weather description.

现在运行代码,瞧! 它将记录天气描述。

一个不同的例子 (A Different Example)

So yeah… Another example! Because why not? This time, I’ll try out the GitHub API. Again just 3 steps.

是的…另一个例子! 因为为什么不呢? 这次,我将尝试GitHub API。 再次只需3个步骤。

First, the API call URL:

首先,API调用URL:

https://api.github.com/users/ahmedrizwan

and the response:

和响应:

{    "login": "ahmedrizwan",    "id": 4357275,    "avatar_url": "https://avatars.githubusercontent.com/u/4357275?v=3",    "gravatar_id": "",    "url": "https://api.github.com/users/ahmedrizwan",    "html_url": "https://github.com/ahmedrizwan",    "followers_url": "https://api.github.com/users/ahmedrizwan/followers",    "following_url": "https://api.github.com/users/ahmedrizwan/following{/other_user}",    "gists_url": "https://api.github.com/users/ahmedrizwan/gists{/gist_id}",    "starred_url": "https://api.github.com/users/ahmedrizwan/starred{/owner}{/repo}",    "subscriptions_url": "https://api.github.com/users/ahmedrizwan/subscriptions",    "organizations_url": "https://api.github.com/users/ahmedrizwan/orgs",    "repos_url": "https://api.github.com/users/ahmedrizwan/repos",    "events_url": "https://api.github.com/users/ahmedrizwan/events{/privacy}",    "received_events_url": "https://api.github.com/users/ahmedrizwan/received_events",    "type": "User",    "site_admin": false,    "name": "ahmed",    "company": null,    "blog": "https://medium.com/@ahmedrizwan",    "location": null,    "email": "ahmedrizwan@outlook.com",    "hireable": true,    "bio": null,    "public_repos": 19,    "public_gists": 0,    "followers": 25,    "following": 16,    "created_at": "2013-05-06T18:32:59Z",    "updated_at": "2016-07-08T11:29:26Z"}

Again, the JSON looks pretty messy.

同样,JSON看起来很混乱。

步骤1:生成Pojos(普通的Java对象) (Step 1: Generate the Pojos (plain old Java objects))

I copied the response and pasted it (yet again):

我复制了响应并将其粘贴到 (再次):

And clicked on Preview.

并单击预览。

Then I copied the Github class into my Project. *music intensifies*

然后,我将Github类复制到我的项目中。 *音乐增强*

步骤2:为端点创建接口 (Step 2: Create Interface for Endpoints)

Now examine the API URL. And I mean, really examine it. You’ll see the endpoint starts from users and ends with the username.

现在检查API URL。 我的意思是,真的要检查一下。 您将看到端点从用户开始,以用户名结束。

https://api.github.com/users/ahmedrizwan

So the interface I created looks like this:

因此,我创建的界面如下所示:

I created a call method, and used @Path annotation to replace the value of {username} in the EndPoint string dynamically.

我创建了一个调用方法,并使用@Path注释动态替换了EndPoint字符串中{username}的值。

第三步:创建适配器和GithubService实例 (Step 3: Create adapter and instance of GithubService)

Here’s the beautiful code for doing just that:

这是执行此操作的漂亮代码:

You’ll notice I’m mapping the user object to String (you can do that with Rx. So Its output becomes:

您会注意到我正在将用户对象映射到String(您可以使用Rx进行此操作。因此,其输出为:

So this is it. Although the article doesn’t cover everything Retrofit and RxAndroid can do (of course), I hope it will get you off to a good start.

就是这样。 尽管本文没有涵盖Retrofit和RxAndroid可以做的所有事情(当然),但我希望它能为您提供一个良好的开端。

Happy coding!

编码愉快!

翻译自:

retrofit2.6.0

转载地址:http://irewd.baihongyu.com/

你可能感兴趣的文章
python中map的排序以及取出map中取最大最小值
查看>>
ROR 第一章 从零到部署--第一个程序
查看>>
<form>标签
查看>>
vue去掉地址栏# 方法
查看>>
Lambda03 方法引用、类型判断、变量引用
查看>>
was集群下基于接口分布式架构和开发经验谈
查看>>
MySQL学习——MySQL数据库概述与基础
查看>>
ES索引模板
查看>>
HDU2112 HDU Today 最短路+字符串哈希
查看>>
JPanel重绘
查看>>
图片放大器——wpf
查看>>
SCALA STEP BY STEP
查看>>
cocos2d-x学习笔记
查看>>
MySql中的变量定义
查看>>
Ruby数组的操作
查看>>
hdu1181暴搜
查看>>
解码字符串 Decode String
查看>>
json学习笔记
查看>>
工具:linux 性能监控工具-nmon
查看>>
fatal error C1853
查看>>