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

ktor_如何在Android应用程序中使用ktor

廉宇
2023-12-01

ktor

In this article, you’ll learn what Ktor is and the benefits of using it. Then you’ll learn how to integrate it into your project. After that, you can read about how to create and execute a Ktor request with code snippets.

在本文中,您将了解什么是Ktor以及使用它的好处。 然后,您将学习如何将其集成到您的项目中。 之后,您可以阅读有关如何使用代码段创建和执行Ktor请求的信息。

The article ends with valuable insights about Ktor. You’ll also find a GitHub Ktor sample repository link at the bottom of this article. Feel free to play around with it.

本文以关于Ktor的宝贵见解结尾。 您还将在本文底部找到GitHub Ktor示例存储库链接。 随便玩吧。

什么是Ktor? (What Is Ktor?)

According to its official website, “Ktor is an open-source framework for building asynchronous servers and clients in connected systems using the powerful Kotlin programming language.” It runs on coroutines and was made by JetBrains.

根据其官方网站 ,“ Ktor是一个开放源代码框架,可使用强大的Kotlin编程语言在连接的系统中构建异步服务器和客户端。” 它在协程上运行,由JetBrains制造

Ktor’s aim is to provide an end-to-end multi-platform application. It’s still a WIP. At present, it has JVM, iOS, JavaScript, and Android clients.

Ktor的目标是提供端到端的多平台应用程序。 仍然是在制品。 目前,它具有JVM,iOS,JavaScript和Android客户端。

为什么选择Ktor联网? (Why Ktor for Networking?)

Despite platform-specific clients, if you try to learn how to use the Ktor client in your native platform, you can easily work with Ktor in other platforms.

尽管有特定于平台的客户端,但是如果您尝试学习如何在本机平台上使用Ktor客户端,则可以轻松地在其他平台上使用Ktor。

For example, as an Android developer first, I tried to use it in native Android applications via Ktor’s Android client. This experience helped me to implement Ktor in multi-platform Kotlin projects.

例如,首先作为一名Android开发人员,我尝试通过Ktor的Android客户端在本机Android应用程序中使用它。 这项经验帮助我在多平台Kotlin项目中实施了Ktor。

Under the hood, Ktor uses coroutines for asynchronous programming to keep the code readable and clean. In addition to that, Ktor has many Kotlinx libraries to help developers with tasks like parsing the response.

在后台,Ktor使用协程进行异步编程,以保持代码的可读性和整洁性。 除此之外,Ktor还有许多Kotlinx库可以帮助开发人员完成诸如解析响应之类的任务。

Using a networking library that can be integrated into multiple platforms is a better solution than choosing platform-specific libraries. As JetBrains develop it, there will be more advanced features and long-term support.

与选择特定于平台的库相比,使用可以集成到多个平台中的网络库是更好的解决方案。 随着JetBrains的发展,将有更多高级功能和长期支持。

积分 (Integration)

To implement Ktor in native Android applications, we need to integrate three libraries:

要在本机Android应用程序中实现Ktor,我们需要集成三个库:

  1. The first one is to integrate Ktor’s Android client.

    第一个是集成Ktor的Android客户端。
  2. Ktor has an interface to make HTTP requests that depends on the engine. Ktor provides a CIO (Coroutine-based I/O) to make it work. We can also use the HttpURLConnection or OkHttp client.

    Ktor具有一个根据引擎发出HTTP请求的接口。 Ktor提供了一个CIO(基于协程的I / O)来使其工作。 我们还可以使用HttpURLConnection或OkHttp客户端。
  3. The final dependency is serializer to parse the response. In this example, we use Ktor’s base JVM serialization client. However, you can choose from other options like the gson Ktor client.

    最终的依赖关系是序列化程序来解析响应。 在此示例中,我们使用Ktor的基本JVM序列化客户端。 但是,您可以从其他选项中选择,例如gson Ktor客户端。

When we bring the pieces together, it looks like this:

当我们将各个部分放在一起时,它看起来像这样:

Ktor integration libraries
Ktor集成库

如何创建Ktor客户端 (How to Create a Ktor Client)

Now that we’ve integrated Ktor in the project, it’s time to code. First, we need to create a Ktor client to make network requests similarly to the retrofit builder.

现在我们已经将Ktor集成到项目中了,是时候编写代码了。 首先,我们需要创建一个Ktor客户端,以与改造生成器类似地发出网络请求。

We use Ktor’s HTTP client and pass the engine in the constructor (in this case, it’s CIO). Then we have to install a specific feature and optionally configure it.

我们使用Ktor的HTTP客户端,并在构造函数中传递引擎(在本例中为CIO)。 然后,我们必须install特定功能并有选择地进行配置 它。

For example, here we use KotlinxSerializer to parse the JSON response. JSON is the feature and KotlinxSerializer is the configuration:

例如,在这里,我们使用KotlinxSerializer解析JSON响应。 JSON是功能,而KotlinxSerializer是配置:

KotlinxSerializer KotlinxSerializer

用协同程序执行Ktor请求 (Executing Ktor Request With Coroutines)

To keep things simple, we’re going to implement a GET request. Here, we’re using the GitHub API to retrieve repositories based on the developer name given by the end-user.

为了简单起见,我们将实现一个GET请求。 在这里,我们使用GitHub API根据最终用户提供的开发人员名称检索存储库。

To make a GET request, we have to use the get inline function on Ktor’s HttpClient with a response data class and request URL, as shown below:

要发出GET请求,我们必须在Ktor的HttpClient上使用带有响应数据类和请求URL的get inline函数,如下所示:

val response = client.get<GitHubSearchResponse>(requestUrl)

get is also a suspend function, so it’ll take care of executing the request on the I/O thread. As it’s a suspend function, it also halts the next step’s execution until we get the response.

get也是一个暂停函数,因此它将负责在I / O线程上执行请求。 由于它是一个暂停函数,因此它也停止了下一步的执行,直到我们得到响应为止。

This is where the real power of Ktor is unleashed. With coroutines, we can execute asynchronous requests sequentially. We need to wrap the request with a try/catch block to capture errors and exceptions. Have a look:

这就是释放Ktor真正力量的地方。 使用协程,我们可以顺序执行异步请求。 我们需要用try/catch块包装请求以捕获错误和异常。 看一看:

Executing get request using Ktor client
使用Ktor客户端执行获取请求

您应该了解的有关Ktor请求的信息 (Things You Should Know About Ktor Requests)

请求类型 (Request type)

In the earlier code snippet, you saw how to execute a GET request. Similarly, we can execute a post request using the post suspend function. Have a look:

在先前的代码片段中,您了解了如何执行GET请求。 同样,我们可以使用post挂起函数执行post请求。 看一看:

Executing GET and POST requests via Ktor client
通过Ktor客户端执行GET和POST请求

As an alternative, we can use the request suspend function and provide the request type in the lambda expression, as shown below:

或者,我们可以使用request暂停功能,并在lambda表达式中提供请求类型,如下所示:

Using Ktor request function to execute various requests types
使用Ktor请求功能执行各种请求类型

标头 (Headers)

One of the basic things we need to add to the request is headers. We can do this in the Ktor request by using the headers block, as shown below:

标头是我们需要添加到请求中的基本内容之一。 我们可以通过使用headers块在Ktor请求中执行此操作,如下所示:

Adding headers to Ktor request
将标题添加到Ktor请求

序列化器 (Serializers)

In the sample above, we used KotlinxSerializer to parse the response. If your project is too large and all your data classes are serialized using other libraries like Gson, Jackson, or JSON, Ktor supports these libraries via their respective clients, as shown below:

在上面的示例中,我们使用KotlinxSerializer解析响应。 如果您的项目太大,并且所有数据类都使用其他库(例如Gson,Jackson或JSON)进行了序列化,则Ktor通过它们各自的客户端支持这些库,如下所示:

Some of Ktor’s serializers
Ktor的一些序列化器

建立客户 (Building the client)

In the example above, we used CIO as an engine. Alternatively, we can use the usual HttpURLConnection or OkHttp client by integrating ktor-client-android or ktor-client-okhttp, respectively.

在上面的示例中,我们使用CIO作为引擎。 另外,我们可以通过分别集成ktor-client-androidktor-client-okhttp来使用通常的HttpURLConnection或OkHttp客户端。

For Android’s HttpURLConnection, we need to implement the following:

对于Android的HttpURLConnection ,我们需要实现以下内容:

// in build.gradle 
implementation "io.ktor:ktor-client-android:$ktor_version"
// in the code, while creating the client
HttpClient(Android)

For OkHttp client, we need to implement the following:

对于OkHttp客户端,我们需要实现以下内容:

// in build.gradle add
implementation "io.ktor:ktor-client-okhttp:$ktor_version"
// in your code, create the client
HttpClient(Okhttp)

奖金 (Bonus)

To better understand Ktor, feel free to try this GitHub sample.

为了更好地了解Ktor,请随时尝试此GitHub示例

To learn more about Kotlin, read the Advanced Programming With Kotlin series.

要了解有关Kotlin的更多信息,请阅读“ 使用Kotlin进行高级编程”系列。

To learn more about Kotlin coroutines and other advanced features of Kotlin, read the following articles:

要了解有关Kotlin协程和Kotlin的其他高级功能的更多信息,请阅读以下文章:

That is all for now. I hope you learned something useful. Thanks for reading!

到此为止。 我希望你学到了一些有用的东西。 谢谢阅读!

翻译自: https://medium.com/better-programming/how-to-use-ktor-in-your-android-app-a99f50cc9444

ktor

 类似资料: