2 回答 2

2

我尚未验证@sftrabbit 提到的算法是否完全遵循这种方法,但您可以使用QUrl::resolved将相对 URL 转换为绝对 URL:

QUrl base("http://www.myhost.com/m/");
qDebug() << base.resolved(QUrl("thelink.html")).toString();
qDebug() << base.resolved(QUrl("../../../thelink.html")).toString();
qDebug() << base.resolved(QUrl("../foo/boo/thelink.html")).toString();

印刷

"http://www.myhost.com/m/thelink.html"
"http://www.myhost.com/thelink.html"
"http://www.myhost.com/foo/boo/thelink.html"

我无法从不适用于 OP 的问题中重现代码示例。唯一的问题是baseUrl代码中缺少该对象。以下SSCCE

#include <QApplication>
#include <QUrl>
#include <QDebug>

int main(int argc, char ** argv) {

    QApplication app( argc, argv );

    QString s("/About-us/");
    QString base("http://qt.digia.com");
    QString urlForReq;
    QUrl baseUrl(base);          // this was missing in the code from the question
    if(!s.startsWith("http:")) {       
        QString uu = QUrl(s).toString();
        QString rurl = baseUrl.resolved(QUrl(s)).toString();
        urlForReq = rurl;
    }
    qDebug() << "urlForReq:" << urlForReq;

    return 0;
}

印刷

urlForReq: "http://qt.digia.com/About-us/"
于 2012-10-29T12:58:47.503 回答
1

您应该有您下载的网页的路径,例如http://www.myhost.com/examples/useless/test.html".

取目录前缀prefix = "http://www.myhost.com/examples/useless/"。每个不以/http://不是相对链接开头的 href,您都可以使用prefix + link.

例如,如果 link = ../foo/boo/thelink.html,则结果为http://www.myhost.com/examples/useless/../foo/boo/thelink.html,浏览器将转换为http://www.myhost.com/examples/useless/boo/thelink.html.

于 2012-10-29T13:02:25.480 回答