删除`www.`来源于问题5.5中的QUrl

Remove `www.` from QUrl in Qt 5.5

本文关键字:中的 QUrl 来源于 www 删除 问题      更新时间:2023-10-16

因此,在程序的另一部分中,我从浏览器中读取了各种URL。假设我有http://www.example.comhttp://example.comhttps://example.com。对于浏览器来说,这三个url是不同的。对我来说,只有"基本"域(example.com)是重要的。

我现在正试图将www从域中剥离,但无法成功。我想使用提供的QUrl库来完成这项工作,而不是检查字符串是否包含www.,然后将其删除。正如你所看到的,这里更多的是一个设计决策;)

这是我目前的申请表。

main.cpp

#include <QApplication>
#include <QDebug>
#include <QUrl>
#include <QList>
int main(int argc, char *argv[])
{
    QList<QUrl> urlList;
    urlList << QUrl("http://example.com/qwe/whoami/123#123141");
    urlList << QUrl("chrome://newtab/");
    urlList << QUrl("favorites://");
    urlList << QUrl("");
    urlList << QUrl("https://www.google.de/");
    urlList << QUrl("https://google.de/");
    urlList << QUrl("https://www.youtube.com/watch?v=XTPGpBBqwe");
    urlList << QUrl("https://youtube.com/watch?v=189273ijadzqiuwejk");
    urlList << QUrl("http://raspberrypi.stackexchange.com/questions/10371/whoisthisyo");
    urlList << QUrl("https://stackoverflow.com/questions/33478464/alfresco-custom");
    urlList << QUrl("http://localhost:3000");
    urlList << QUrl("localhost:3000");
    for (int i = 0; i < urlList.count(); i++) {
        qDebug() << "[" << i+1 << "] " << urlList[i].host();
    }

    return 0;
}

谢谢你的帮助!

没有现成的功能。

我能想到的最好的解决方案是替换URL的主机部分开头的"www."(如果存在的话)。

请注意,您不应该在主机中甚至在URL的其余部分中删除字符串"www."的任何其他出现,因此我们检查QUrl::host()是否以"www."开头,然后从中删除这四个字符。

还要注意的是,从技术上讲,这会更改主机名,从而导致您访问不同的网站。(尽管实际上,出于可用性的原因,每个网站都应该提供带有或不带有www.子域前缀的相同内容。)此外,在某些特殊情况下,这可能会导致完全出乎意料的结果,例如www.甚至不是子域:域www.com将只产生com

QUrl remove_www(QUrl url) {
    QString host = url.host();
    if (host.startsWith("www."))
        host = host.mid(4); // = remove first 4 chars
    url.setHost(host);
    return url;
}

然后使用此函数的返回值:

for (int i = 0; i < urlList.count(); i++) {
    qDebug() << "[" << i+1 << "] " << remove_www(urlList[i]);
}