Qt 6.7和Forward中的RESTful客户端应用程序

RESTful Client Applications in Qt 6.7 and Forward

Qt 6.7和Forward中的RESTful客户端应用程序

March 15, 2024 by Juha Vuolle | Comments

2024年3月15日 Juha Vuolle 发表|评论

Qt 6.7 introduces convenience improvements for implementing typical RESTful/HTTP client applications. The goal was/is to reduce the repeating networking boilerplate code by up to 40% by addressing the small but systematically repeating needs in a more convenient way. 

These include a new QHttpHeaders class for representing HTTP headers, QNetworkRequestFactory for creating API-specific requests,  QRestAccessManager class for addressing small but often-repeating pieces of code, and QRestReply class for extracting the data from replies and checking for errors. QNetworkRequestFactory, QRestAccessManager, and QRestReply are released as Technical Previews in Qt 6.7.

其中包括一个新的QHttpHeaders类,用于表示HTTP头,QNetworkRequestFactory,用于创建特定于API的请求,QRestAccessManager类,用于处理较小但经常重复的代码片段,以及QRestReply类,用于从回复中提取数据并检查错误。QNetworkRequestFactory、QRestAccessManager和QRestReply在Qt 6.7中作为技术预览发布。

Below is a screenshot of the Qt Colorpalette Client example application, which uses these new enablers. The client application interfaces a REST API and visualizes the 'color' and 'user' resources.

​下面是Qt Colorpalette Client示例应用程序的屏幕截图,该应用程序使用了这些新的启用程序。客户端应用程序与REST API接口,并可视化“颜色”和“用户”资源。

colorpaletteclient

REST Briefly

REST简介

REST is an architectural style used by most of the networked applications we use today. ‘REST’ is not a strict technical specification but rather a set of constraints and recommendations on organizing and accessing resources. Technically, it boils down to sending and serving HTTP requests, making it somewhat common to talk about HTTP clients and RESTful clients interchangeably.  

REST是我们今天使用的大多数网络应用程序所使用的一种体系结构风格。”REST不是一个严格的技术规范,而是一组关于组织和访问资源的约束和建议。从技术上讲,它可以归结为发送和服务HTTP请求,这使得交换地谈论HTTP客户端和RESTful客户端变得有些常见。

Since Qt 4.4 (2008) the main class for developing RESTful/HTTP client applications on the C++ side is the QNetworkAccessManager. With it, you can issue HTTP requests and use signal-slot connections to handle the responses.

​自Qt 4.4(2008)以来,在C++端开发RESTful/HTTP客户端应用程序的主要类是QNetworkAccessManager。有了它,可以发出HTTP请求并使用信号槽连接来处理响应。

On the QML and Javascript side, there’s an XmlHttpRequests class for a similar purpose. More complex QML applications also use the C++ QNetworkAccessManager and bridge/expose the networking to QML as data and control types/elements.

​在QML和Javascript方面,有一个用于类似目的的XmlHttpRequests类。更复杂的QML应用程序还使用C++QNetworkAccessManager,并将网络作为数据和控制类型/元素桥接/暴露给QML。

New in Qt 6.7: QHttpHeaders

​Qt 6.7:QHttpHeaders中的新增功能

HTTP headers in Qt are represented by a QMap, QHash, list of pairs, QMultiMap, or QMultiHash. This works, but the exact type is API-specific and doesn’t allow for common header convenience operations, performance optimizations, or, for example, checking that header names and values are valid according to RFC specifications.

Qt中的HTTP报头由QMap、QHash、对列表、QMultiMap或QMultiHash表示。这是有效的,但确切的类型是特定于API的,并且不允许常见的报头方便操作、性能优化,例如,根据RFC规范检查报头名称和值是否有效。

Qt 6.7 introduces QHttpHeaders class to represent HTTP headers. For now, the class is mostly used internally. Later Qt releases will expand the public networking APIs to support this class.

​Qt 6.7引入了QHttpHeaders类来表示HTTP报头。目前,该类主要在内部使用。稍后的Qt版本将扩展公共网络API以支持此类。

An example of an internal performance optimization that this enables is that we can internally use enums instead of strings to represent any of the 100+ well-known headers. This makes lookups and storage computationally more efficient.

这样可以实现内部性能优化的一个例子是,我们可以在内部使用枚举而不是字符串来表示100多个已知的报头中的任何一个。这使得查找和存储在计算上更加高效。

New in Qt 6.7: QNetworkRequestFactory

Qt 6.7新增:QNetworkRequestFactory

Most REST server APIs require information that repeats from request to request: the URL, query parameters, SSL config, and authentication details. These requests also have parts that typically change from request to request: the resource path and query parameters. 

大多数REST服务器API需要从一个请求到另一个请求重复的信息:URL、查询参数、SSL配置和身份验证详细信息。这些请求还有一些部分通常会随着请求的不同而变化:资源路径和查询参数。

QNetworkRequestFactory allows you to define the common parameters only once and, after that, pass only request-specific parameters when creating new requests. The created requests are then passed on to QNetworkAccessManager or QRestAccessManager. 

QNetworkRequestFactory允许只定义一次通用参数,然后在创建新请求时只传递特定于请求的参数。然后将创建的请求传递给QNetworkAccessManager或QRestAccessManager。

A typical use would be to have a factory for each API of interest:

一种典型的用途是为每个感兴趣的API建立一个工厂:

// Instantiate a network access manager somewhere in the application
QNetworkAccessManager manager;
// … initialize manager

// Instantiate a factory somewhere suitable in the application
QNetworkRequestFactory exampleApi{ {"https://example.com/v1"_L1} };
// Set bearer token
exampleApi.setBearerToken("my_token");
// Fill common headers
QHttpHeaders commonHeaders;
exampleApi.setCommonHeaders(commonHeaders);
// … set query parameters, etc …
// Create and issue request to “https://example.com/v1/models”
manager.get(exampleApi.createRequest("models"_L1));

The QNetworkRequestFactory class will be released in Qt 6.7 as a Technical Preview, and the API has already been further amended for Qt 6.8, thanks to the early user feedback. 

QNetworkRequestFactory类将在Qt6.7版中作为技术预览版发布,由于早期用户反馈,API已针对Qt6.8版进行了进一步修改。

New Qt 6.7: QRestAccessManager and QRestReply

​新Qt6.7:QRestAccessManager和QRestReply

QRestAccessManager and related QRestReply are thin, non-owning, convenience wrappers on top of QNetworkAccessManager and QNetworkReply. They streamline the typical RESTful/HTTP client needs: 

QRestAccessManager和相关的QRestReply是QNetworkAccessManager和QNetworkReply之上的精简、无所有权、方便的包装器。它们简化了典型的RESTful/HTTP客户端需求:

  • Accept JSON and other types directly as request data
  • 直接接受JSON和其他类型作为请求数据
  • Provide JSON and other types (notably text) on the reply
  • 在回复中提供JSON和其他类型(尤其是文本)
  • Error handling (distinguish between network errors and HTTP errors)
  • 错误处理(区分网络错误和HTTP错误)
  • Accept contextful callbacks directly when issuing the request
  • 发出请求时直接接受contextful回调
  • And others, including named API for sending patch() requests
  • 以及其他,包括用于发送patch()请求的命名API

While these improvements aren’t necessarily very large on their own, they reduce the required boilerplate and head-scratching.  Below is an example of posting and receiving JSON. It reduces the needed code in several ways, enhancing convenience:

虽然这些改进本身不一定很大,但它们减少了所需的样板和挠头。下面是发布和接收JSON的示例。它以多种方式减少了所需的代码,增强了便利性:

  • Send the JSON data directly (‘myJson’). There is no need to convert manually or set ‘Content-Type:application/json’ header.
  • 直接发送JSON数据('myJson')。无需手动转换或设置“Content-Type:application/json”报头。
  • Define the callback directly (‘this’ is used as context object to clean up if ‘this’ is deleted)
  • 直接定义回调(如果删除了“this”,则使用“this”作为上下文对象进行清理)
  • Read the response JSON directly (‘readJson()’).  There is no need to write the conversion from a QByteArray. The JSON parsing error is also available if needed. This example skips success checks, but it could be done with ‘reply.isSuccess()’ 
  • 直接读取响应JSON(“readJson()”)。不需要从QByteArray写入转换。如果需要,JSON解析错误也可用。此示例跳过成功检查,但可以使用“reply.isSuccess()”完成
manager->post(request, myJson, this, [this](QRestReply &reply) {
    if (auto json = reply.readJson()) {
        // use *json
    }
});

If the expected data were text, it could’ve been read as it arrives (streaming); QRestReply implements streaming text decoding and uses the indicated ‘charset’ parameter (e.g., UTF-8).

如果预期的数据是文本,那么它可能在到达时被读取(流式传输);QRestReply实现流式文本解码,并使用指示的“字符集”参数(例如UTF-8)。

Note: since these are mere non-owning convenience wrappers, you can still use your pre-existing QNetworkAccessManager code and, for instance, wrap the received QNetworkReply* in a QRestReply.

注意:由于这些只是非拥有的便利包装器,仍然可以使用预先存在的QNetworkAccessManager代码,例如,将接收到的QNetwworkReply*包装在QRestReply中。

QRestAccessManager and QRestReply are released as Technical Previews in Qt 6.7.

QRestAccessManager和QRestReply在Qt 6.7中作为技术预览发布。

Future

未来

There are many more related items in the planning stage, and feedback for them is welcome:

在规划阶段还有许多相关项目,欢迎对其进行反馈:

QHttpMultipart convenience API for form-data
QtNetworkAuthorization module improvements
QML/Javascript Fetch()
OpenAPI client generator support
OpenAPI server generator support
General ideation and feedback

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值