api端点
As an Android app developer, there were many instances when I had to depend on a local JSON file to not block app development since the API endpoints were still in progress. It is easier to go with a JSON file since the JSON design is generally finalized at the very beginning of a sprint.
作为一个Android应用程序开发人员,在很多情况下,由于API端点仍在进行中,因此我不得不依赖本地JSON文件来阻止应用程序开发。 使用JSON文件更容易,因为JSON设计通常在冲刺的开始就完成了。
Once the API endpoints are ready, the challenging part is, integrating API endpoints quickly without spending a lot of time on it. This includes removing all the code that was required to use local JSON files in the first place. Or having an if/else loop to make sure that local JSON files are used only in debug version of the app.
一旦准备好API端点,最具挑战性的部分就是快速集成API端点,而无需花费大量时间。 这包括首先删除使用本地JSON文件所需的所有代码。 或者使用if / else循环来确保仅在应用程序的调试版本中使用本地JSON文件。
However, there needs to be a better, cleaner, and concise way of writing code for this implementation.
但是,需要一种更好,更简洁的简洁方法来编写此实现的代码。
Ideally, toggling between an API endpoint and Local JSON file should be as easy as commenting a single line of code. And this is what we would try to achieve by the end of this article!
理想情况下,在API终结点和本地JSON文件之间切换应该像注释一行代码一样容易。 这就是我们在本文末尾要实现的目标!
We will be using Retrofit in this example since it is the most widely used networking library today.
在本示例中,我们将使用Retrofit,因为它是当今使用最广泛的网络库。
入门 (Getting Started)
Let’s create an Interceptor which is responsible for intercepting HTTP requests and mocking a response from the user-specified local JSON file.
让我们创建一个拦截器,该拦截器负责拦截HTTP请求并模拟来自用户指定的本地JSON文件的响应。
This is how the MockRequestInterceptor class looks like:
这是MockRequestInterceptor类的样