QT QUrl

1.概述

QUrl类为使用url提供了一个方便的接口。

它可以以编码和未编码的形式解析和构造url。QUrl还支持国际化域名(idn)。

使用QUrl最常见的方法是通过传递一个QString来通过构造函数初始化它。否则,也可以使用setUrl()。

url可以用两种形式表示:编码的或未编码的。未编码的表示适合显示给用户,但编码的表示通常是您将发送给web服务器的内容。例如,application .xml的未编码的URL“http://bühler.example.com/List”将作为“http://xn--bhler-kva.example.com/List%20of%20applicants.xml”发送到服务器。

URL也可以通过调用setScheme()、setUserName()、setPassword()、setHost()、setPort()、setPath()、setQuery()和setFragment()来一块一块地构造。还提供了一些方便的函数:setAuthority()设置用户名、密码、主机和端口。setUserInfo()一次性设置用户名和密码。

调用isValid()检查URL是否有效。这可以在构建URL期间的任何时候完成。如果isValid()返回false,您应该在继续之前清除()URL,或者使用setUrl()重新解析一个新的URL。

通过使用QUrlQuery类及其方法QUrlQuery::setQueryItems()、QUrlQuery::addQueryItem()和QUrlQuery::removeQueryItem()来构造查询是特别方便的。使用QUrlQuery:: setquerydelimiter()定制用于生成查询字符串的分隔符。

为了方便生成编码的URL字符串或查询字符串,有两个调用fromPercentEncoding()和toPercentEncoding()的静态函数,它们处理qstring的百分比编码和解码。

调用isRelative()将告诉URL是否是相对的。相对URL可以通过将其作为参数传递给resolved()来解析,后者返回一个绝对URL。isParentOf()用于确定一个URL是否是另一个URL的父URL。

fromLocalFile()通过解析本地文件路径来构造一个QUrl。toLocalFile()将URL转换为本地文件路径。

人类可读的URL表示是通过toString()获取的。这种表示适合以未编码的形式向用户显示URL。但是,toEncoded()返回的编码表单用于内部使用,传递给web服务器、邮件客户端等等。这两种表单在技术上是正确的,并明确地表示相同的URL——实际上,将表单传递给QUrl的构造函数或setUrl()将产生相同的QUrl对象。

QUrl符合RFC 3986(统一资源标识符:通用语法)的URI规范,并包含RFC 1738(统一资源定位器)的模式扩展。QUrl中的大小写折叠规则符合RFC 3491 (Nameprep:用于国际化域名(IDN)的Stringprep配置文件)。它也与freedesktop.org的文件URI规范兼容,前提是语言环境使用UTF-8对文件名进行编码(IDN要求)。


2.错误检查

QUrl能够在解析URL时检测URL中的许多错误,或者当URL的组件使用单独的设置方法(如setScheme(), setHost()或setPath())设置时。如果解析或setter函数成功,则将丢弃先前记录的任何错误条件。

默认情况下,QUrl设置方法以QUrl::TolerantMode操作,这意味着它们接受一些常见的错误和数据的错误表示。另一种解析方法是QUrl::StrictMode,它将应用进一步的检查。关于解析模式的区别,请参见QUrl::ParsingMode。

QUrl只检查与URL规范的一致性。它不试图验证高级协议url是否为其他地方的处理程序所期望的格式。例如,以下uri都被QUrl认为是有效的,即使它们在使用时没有意义:

“http: / filename.html”
“mailto: / / example.com”

当解析器遇到错误时,它通过使isValid()返回false和toString() / toEncoded()返回一个空字符串来通知事件。如果有必要向用户显示URL解析失败的原因,可以通过调用errorString()从QUrl获得错误条件。请注意,此消息是高度技术性的,可能对最终用户没有意义。

QUrl只能记录一个错误条件。如果发现多个错误,则不确定报告哪个错误。


3.字符转换

在处理url和字符串时,请遵循以下规则以避免错误的字符转换:

当从QByteArray或char*创建一个包含URL的QString时,总是使用QString::fromUtf8()。

4.成员类型说明

4.1

enum QUrl::ComponentFormattingOption
flags QUrl::ComponentFormattingOptions

组件格式化选项定义了URL的组件在作为文本输出时如何格式化。当在toString()和toEncoded()中使用时,它们可以与来自QUrl:: formatingoptions的选项组合。

ConstantValueDescription
QUrl::PrettyDecoded0x000000The component is returned in a "pretty form", with most percent-encoded characters decoded. The exact behavior of PrettyDecoded varies from component to component and may also change from Qt release to Qt release. This is the default.
QUrl::EncodeSpaces0x100000Leave space characters in their encoded form ("%20").
QUrl::EncodeUnicode0x200000Leave non-US-ASCII characters encoded in their UTF-8 percent-encoded form (e.g., "%C3%A9" for the U+00E9 codepoint, LATIN SMALL LETTER E WITH ACUTE).
QUrl::EncodeDelimiters0x400000 | 0x800000Leave certain delimiters in their encoded form, as would appear in the URL when the full URL is represented as text. The delimiters are affected by this option change from component to component. This flag has no effect intoString() or toEncoded().
QUrl::EncodeReserved0x1000000Leave US-ASCII characters not permitted in the URL by the specification in their encoded form. This is the default on toString() and toEncoded().
QUrl::DecodeReserved0x2000000Decode the US-ASCII characters that the URL specification does not allow to appear in the URL. This is the default on the getters of individual components.
QUrl::FullyEncodedEncodeSpaces | EncodeUnicode | EncodeDelimiters | EncodeReservedLeave all characters in their properly-encoded form, as this component would appear as part of a URL. When used with toString(), this produces a fully-compliant URL in QString form, exactly equal to the result of toEncoded()
QUrl::FullyDecodedFullyEncoded | DecodeReserved | 0x4000000Attempt to decode as much as possible. For individual components of the URL, this decodes every percent encoding sequence, including control characters (U+0000 to U+001F) and UTF-8 sequences found in percent-encoded form. Use of this mode may cause data loss, see below for more information.


EncodeReserved和DecodeReserved的值不应该在一个调用中一起使用。如果发生这种情况,该行为是未定义的。它们是作为单独的值提供的,因为“漂亮模式”对于保留字符的行为在某些组件上是不同的,特别是在完整URL上。


完整的解码

FullyDecoded模式类似于Qt 4中返回QString的函数的行为。X,因为每个字符都代表自己,没有任何特殊意义。即使对于百分比字符('%')也是如此,它应该解释为字面上的百分比,而不是百分比编码序列的开始。在所有其他解码模式中,相同的实际字符由序列“%25”表示。

当重新应用使用QUrl::FullyDecoded得到的数据到一个QUrl时,必须小心使用参数QUrl::DecodedMode的setter(如setPath()和setUserName())。如果不这样做,可能会导致将百分比字符('%')重新解释为百分比编码序列的开头。

当URL的部分在非URL上下文中使用时,这种模式非常有用。例如,要在FTP客户端应用程序中提取用户名、密码或文件路径,应该使用FullyDecoded模式。

应该谨慎使用这种模式,因为有两个条件不能在返回的QString中可靠地表示。它们是:

  • 非UTF-8序列:url可能包含不构成有效UTF-8序列的百分比编码字符序列。由于url需要使用UTF-8解码,任何解码器失败都会导致QString包含一个或多个序列存在的替换字符。
  • 编码分隔符:还允许url区分文字形式的分隔符和百分比形式的分隔符。这在查询中最常见,但在URL的大多数部分中是允许的。

下面的例子说明了这个问题:

QUrl original("http://example.com/?q=a%2B%3Db%26c");
QUrl copy(original);
copy.setQuery(copy.query(QUrl::FullyDecoded), QUrl::DecodedMode);

qDebug() << original.toString();   // prints: http://example.com/?q=a%2B%3Db%26c
qDebug() << copy.toString();       // prints: http://example.com/?q=a+=b&c


如果这两个url是通过HTTP GET使用的,web服务器的解释可能会不同。在第一种情况下,它将解释为一个参数,键为“q”,值为“a+=b&c”。在第二种情况下,它可能被解释为两个参数,一个键为“q”,值为“a =b”,另一个键为“c”,没有值。

该枚举在Qt 5.0中被引入或修改。

componentformatingoptions类型是QFlags< componentformatingoption >的typedef。它存储componentformatingoption值的OR组合。

参见QUrl:: FormattingOptions。

4.2


enum QUrl:: ParsingMode
解析模式控制QUrl解析字符串的方式。

ConstantValueDescription
QUrl::TolerantMode0QUrl will try to correct some common errors in URLs. This mode is useful for parsing URLs coming from sources not known to be strictly standards-conforming.
QUrl::StrictMode1Only valid URLs are accepted. This mode is useful for general URL validation.
QUrl::DecodedMode2QUrl will interpret the URL component in the fully-decoded form, where percent characters stand for themselves, not as the beginning of a percent-encoded sequence. This mode is only valid for the setters setting components of a URL; it is not permitted in the QUrl constructor, infromEncoded() or in setUrl(). For more information on this mode, see the documentation for QUrl::FullyDecoded.


在TolerantMode中,解析器具有以下行为:

  • 空格和"%20":将接受未编码的空格字符,并将被视为等同于"%20"。
  • 单个"%"字符:如果百分比字符"%"后面没有两个十六进制字符(例如"13% coverage.html"),则会被"%25"代替。请注意,一个单独的“%”字符将触发所有百分比字符的校正模式。
  • 保留字符和不保留字符:编码后的URL应该只包含少数字符;所有其他字符都应该是百分比编码的。在TolerantMode中,这些字符将被接受,如果它们在URL中找到:空格/双引号/ "<" / ">" / "" / "^" / " ' " / "{" / "|" / "}"这些相同的字符可以被再次解码,通过传递QUrl::DecodeReserved给toString()或toEncoded()。在单个组件的getter中,这些字符通常以解码形式返回。

在StrictMode模式下,如果发现解析错误,isValid()将返回false, errorString()将返回描述错误的消息。如果检测到多个错误,则不确定报告哪个错误。

注意,对于解析用户输入,TolerantMode通常是不够的,因为用户输入通常包含更多的错误和期望,解析器无法处理这些错误和期望。在处理直接来自用户的数据时——而不是来自数据传输源(如其他程序)的数据——建议使用fromUserInput()。

参见fromUserInput()、setUrl()、toString()、toEncoded()和QUrl:: formatingoptions。

4.3

enum QUrl::UrlFormattingOption
flags QUrl::FormattingOptions

格式化选项定义了URL作为文本输出时是如何格式化的。

ConstantValueDescription
QUrl::None0x0The format of the URL is unchanged.
QUrl::RemoveScheme0x1The scheme is removed from the URL.
QUrl::RemovePassword0x2Any password in the URL is removed.
QUrl::RemoveUserInfoRemovePassword | 0x4Any user information in the URL is removed.
QUrl::RemovePort0x8Any specified port is removed from the URL.
QUrl::RemoveAuthorityRemoveUserInfo | RemovePort | 0x10
QUrl::RemovePath0x20The URL's path is removed, leaving only the scheme, host address, and port (if present).
QUrl::RemoveQuery0x40The query part of the URL (following a '?' character) is removed.
QUrl::RemoveFragment0x80
QUrl::RemoveFilename0x800The filename (i.e. everything after the last '/' in the path) is removed. The trailing '/' is kept, unless StripTrailingSlash is set. Only valid if RemovePath is not set.
QUrl::PreferLocalFile0x200If the URL is a local file according to isLocalFile() and contains no query or fragment, a local file path is returned.
QUrl::StripTrailingSlash0x400The trailing slash is removed if one is present.
QUrl::NormalizePathSegments0x1000Modifies the path to remove redundant directory separators, and to resolve "."s and ".."s (as far as possible).

请注意Nameprep中的大小写折叠规则,这是QUrl遵循的,要求主机名总是转换为小写,而不管使用的Qt:: formatingoptions。

来自QUrl:: componentformatingoptions的选项也是可能的。

formatingoptions类型是QFlags< urlformatingoption >的类型定义。它存储urlformatingoption值的OR组合。

参见QUrl:: ComponentFormattingOptions。

4.4

enum QUrl:: UserInputResolutionOption
旗帜QUrl:: UserInputResolutionOptions

用户输入解析选项定义了fromUserInput()应该如何解释字符串,这些字符串可以是相对路径,也可以是HTTP URL的简短形式。例如,file.pl可以是本地文件,也可以是URL http://file.pl。

ConstantValueDescription
QUrl::DefaultResolution0The default resolution mechanism is to check whether a local file exists, in the working directory given to fromUserInput, and only return a local path in that case. Otherwise a URL is assumed.
QUrl::AssumeLocalFile1This option makes fromUserInput() always return a local path unless the input contains a scheme, such as http://file.pl. This is useful for applications such as text editors, which are able to create the file if it doesn't exist.

该枚举在Qt 5.4中被引入或修改。

UserInputResolutionOptions类型是QFlags<UserInputResolutionOption>的类型定义。它存储UserInputResolutionOption值的OR组合。

参见fromUserInput()。

QUrlQt中用于处理URL的类。它可以解析和构建URL,支持各种协议(如http,ftp,file等),并提供了一些方便的方法来获取URL的各个部分。 下面是一些常见的QUrl使用方法: 1. 创建一个QUrl对象 ```cpp QUrl url("http://www.example.com/path/file.html"); ``` 2. 获取URL的各个部分 ```cpp QString scheme = url.scheme(); // 获取协议部分,如http QString host = url.host(); // 获取主机部分,如www.example.com int port = url.port(); // 获取端口号,如果没有指定则返回-1 QString path = url.path(); // 获取路径部分,如/path/file.html QString query = url.query(); // 获取查询字符串,如key=value&name=John QUrlFragment fragment = url.fragment(); // 获取片段标识符,如section1 ``` 3. 修改URL的各个部分 ```cpp url.setScheme("https"); // 修改协议部分为https url.setHost("example.com"); // 修改主机部分为example.com url.setPort(8080); // 修改端口号为8080 url.setPath("/newpath/file.html"); // 修改路径部分为/newpath/file.html url.setQuery("key=newvalue"); // 修改查询字符串为key=newvalue url.setFragment("section2"); // 修改片段标识符为section2 ``` 4. 判断URL是否合法 ```cpp bool isValid = url.isValid(); // 判断URL是否合法,如果合法则返回true ``` 5. 解析URL参数 ```cpp QUrlQuery query(url.query()); // 将查询字符串解析为QUrlQuery对象 QString value = query.queryItemValue("key"); // 获取查询参数key的值 ``` 6. 构建URL ```cpp QUrl url; url.setScheme("http"); url.setHost("www.example.com"); url.setPath("/path/file.html"); url.setQuery("key=value"); QString urlString = url.toString(); // 将QUrl对象转换为字符串,返回http://www.example.com/path/file.html?key=value ``` 以上是QUrl的一些常见用法,更多详细用法可以参考Qt官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Allen Roson

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值