当前位置: 首页 > 工具软件 > Ktor > 使用案例 >

ktor_将改造迁移到Ktor

晏志明
2023-12-01

ktor

Ktor is a coroutine-based networking framework by Jetbrains written in Kotlin. It works with Kotlin Multiplatform, allowing you to share networking code between different platforms.This article explores the framework set up and the connection with a REST API in your Android project.

Ktor是Jetbrains用Kotlin编写的基于协程的网络框架。 它可与Kotlin Multiplatform一起使用 ,使您可以在不同平台之间共享网络代码。本文探讨了框架设置以及与Android项目中REST API的连接。

添加Ktor (Adding Ktor)

The Ktor client consists of two main parts:

Ktor客户端包括两个主要部分:

  1. Engine: The HTTP client used to perform network requests. This article uses the Android/JVM OkHttp engine.

    引擎:用于执行网络请求的HTTP客户端。 本文使用Android / JVM OkHttp引擎。

  2. Serialization: Processing request and response payloads as JSON and serializing them from/to your data models, using kotlinx Serialization.

    序列化:使用kotlinx序列化将请求和响应负载作为JSON进行处理,并将它们从数据模型中进行序列化。

Add the dependencies to your project’s Gradle with the following artifacts:

使用以下工件将依赖项添加到项目的Gradle中:

implementation "io.ktor:ktor-client-okhttp:$ktorVersion"implementation "io.ktor:ktor-client-json:$ktorVersion"implementation "io.ktor:ktor-client-serialization-jvm:$ktorVersion" implementation "io.ktor:ktor-client-logging-jvm:$ktorVersion"

At the time of writing, the latest ktor version is 1.3.2

在撰写本文时,最新的ktor版本是 1.3.2。

HTTP客户端 (The HTTP Client)

The start point for every network request is the Ktor Http Client.

每个网络请求的起点都是Ktor Http客户端。

The example above consists of the following parts:

上面的示例包括以下部分:

  • OkHttp Engine [line 2]: It is required for creating the Http Client. We chose the OkHttp engine to keep compatibility with our Interceptors. However, other engines like URLSession for iOS or the kotlin-common CIO are also available.

    OkHttp引擎 [第2行]:创建Http客户端是必需的。 我们选择OkHttp引擎来保持与我们的拦截器的兼容性。 然而,其他引擎,如URLSession为iOS或Kotlin常见CIO 也可提供

  • JsonFeature [lines 4–6]: Handles the JSON conversion between the request/response body and your data models. This example assumes you have already included Kotlinx Serialization to your project; more information about its setup and usage can be found here.

    JsonFeature [4-6行]:处理请求/响应主体与数据模型之间的JSON转换。 本示例假定您已经将Kotlinx序列化包含到您的项目中; 有关其设置和用法的更多信息,请参见此处

  • Logging (optional) [lines 8–15]: Logs ongoing network requests.

    记录(可选) [8-15行]: 记录正在进行的网络请求。

  • Timeout [lines 16–21]: Sets default timeouts for your connections.

    超时 [第16-21行] 设置连接的默认超时。

  • Default Request (optional) [lines 23–28]: Appends specific configurations to all requests.

    默认请求(可选) [23-28行]:将特定配置附加到所有请求。

  • Engine Configurations (optional) [lines 30–32]: Sets any engine-specific configurations for the Client. The example shows adding an OkHttp Interceptor to log all requests in curl format.

    引擎配置(可选) [第30–32行]:为客户端设置任何引擎特定的配置。 该示例显示添加OkHttp拦截器以curl格式记录所有请求。

Inject the client to the modules requiring it, either re-using the same single client or providing a factory method.

重新使用相同的单个客户端或提供工厂方法,将客户端注入需要它的模块。

序列化 (Serialization)

To easily read and manipulate the API response, create a Kotlin class to hold the data. Annotate it with @Serializable for Kotlinx Serialization to match the JSON response with the class’ properties.

为了轻松读取和处理API响应,请创建一个Kotlin类来保存数据。 使用@Serializable进行注释以进行Kotlinx序列化,以将JSON响应与类的属性进行匹配。

Item Model
项目型号

The above model states the following configurations:

上面的模型陈述了以下配置:

  • The JSON must contain an id property of type Int.

    JSON 必须包含一个Int类型的id属性。

  • All properties with a default value (= null) can be missing on the JSON.

    具有默认值的所有属性( = null BE) 失踪 在JSON上

  • Properties with a nullable type (String?, Boolean?,…) can have a value of null in the JSON.

    可以为空的类型( String?Boolean? ,…)的属性在JSON中可以具有null值。

  • Fields annotated with@SerialName map different names between the JSON key (value = “share_link”) and the class property (shareUrl).

    @SerialName注释的字段在JSON密钥( value = “share_link” )和类属性( shareUrl )之间映射了不同的名称。

网络请求 (Network Requests)

Using the Http Client, make the first request, for example, to get a list of items:

例如,使用Http Client发出第一个请求,以获取项目列表:

The request consists of the following parts:

该请求包括以下部分:

  1. Http Method: Use the HTTP Method you need, for example, .get.

    Http方法:使用所需的HTTP方法。 得到

  2. Deserialization (optional): The data model that matches the response. In this case List<Item>.

    反序列化(可选):与响应匹配的数据模型。 在这种情况下, List <Item>

    If you don’t want to map your response into a specific model, you can just

    如果您不想将响应映射到特定模型中,则可以

    skip it or use HttpResponse instead. The latter will give you access to the status code (with status.value) and the body as a String (with readText()).

    跳过它或改用HttpResponse 。 后者将使您可以访问状态码(带有status.value )和正文作为字符串(带有readText() )。

  3. URL: The endpoint’s URL. As a good practice, keep all your URLs in a separate file.

    URL :端点的URL。 好的做法是,将所有URL放在单独的文件中。

  4. Parameters (optional): If needed, provide additional parameters for the request inside the method’s block.

    参数(可选) :如果需要,在方法的块内为请求提供其他参数。

This method call returns a list of items because get is a suspend function and thus it must be called inside a coroutine scope.Ensure you use a context not bound to the main thread, for example, Dispatchers.IO to execute your network requests.If you have not included coroutines in your project, go through the setup here.

该方法调用返回一个项目列表,因为get是一个暂停函数,因此必须在协程范围内调用它。确保使用未绑定到主线程的上下文(例如Dispatchers.IO)执行网络请求。如果您的项目中未包含协程,请在 此处 进行设置

错误处理 (Error handling)

If anything goes wrong during the network call, the coroutine will throw an exception. You can catch that using a try/catch block.The request may fail for the following reasons:

如果在网络通话期间发生任何问题,协程将引发异常。 您可以使用try / catch块来捕获该请求。由于以下原因,请求可能会失败:

  • The response was not successful (status code different from the 2xx range).

    响应不成功(状态代码不同于2xx范围)。
  • Error deserializing the response.

    反序列化响应时出错。
  • No network connection.

    无网络连接。
  • Request Timeout.

    请求超时。

Below you will find a method performing an email login for a given user.

在下面,您将找到一种为给定用户执行电子邮件登录的方法。

Login Error Handling example
登录错误处理示例

奖励:分段上传 (Bonus: Multipart File Upload)

Use the convenience function submitFormWithBinaryData to launch a multipart request with Ktor:

使用便捷功能submitFormWithBinaryData与Ktor推出multipart请求:

Ensure the Http Client for multipart requests does not have any logging interceptors and does not set the Content-Type for the request.

确保用于多部分请求的Http客户端没有任何日志记录拦截器,并且未设置请求的Content-Type。

最后的想法 (Final Thoughts)

Ktor is a stable network library, it has all the options needed to connect with REST APIs and is ready for production. Nevertheless, it does not provide the same level of abstraction and simplicity as Retrofit.If you are looking for an Android/JVM-only library, stick with Retrofit. However, if you want to enter the KMP world, Ktor is the way to go.

Ktor是一个稳定的网络库,它具有连接REST API所需的所有选项,并已准备好投入生产。 但是,它不能提供与Retrofit相同的抽象和简化级别。如果您正在寻找仅Android / JVM的库,请坚持使用Retrofit。 但是,如果您想进入KMP领域,则可以选择Ktor。

In the next article, we will explore how to move over all the shared code to a Kotlin Multiplatform project and call it from our native Android and iOS projects.

在下一篇文章中,我们将探讨如何将所有共享代码移至Kotlin Multiplatform项目,并从我们的本机Android和iOS项目中调用它。

翻译自: https://medium.com/l-r-engineering/migrating-retrofit-to-ktor-93bdaf58d7d4

ktor

 类似资料: