Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How in Qt5 to check if url is available?

Using Qt5, how to simply check if given url is available?

Not using special functions for signal slots, but simply using something like bool isUrlAvailable(QString url), are there any function like this?

Update QUrl.isValid() is incorrect answer, it is just checks if url is correctly formed.

Update 2 QUrl.host() is incorrect answer too, it is just returns host part of given url, it does not check for its availability.

Update 3 pinging host is also incorrect, because url may be available, but does not accept icmp echo (=ping)

like image 470
vladon Avatar asked Oct 28 '25 09:10

vladon


1 Answers

Yes, you can do a HEAD request to a given URL.

bool urlExists (QString url_string) {
    QUrl url(url_string);
    QTcpSocket socket;
    socket.connectToHost(url.host(), 80);
    if (socket.waitForConnected()) {
        socket.write("HEAD " + url.path().toUtf8() + " HTTP/1.1\r\n"
                     "Host: " + url.host().toUtf8() + "\r\n\r\n");
        if (socket.waitForReadyRead()) {
            QByteArray bytes = socket.readAll();
            if (bytes.contains("200 OK")) {
                return true;
            }
        }
    }
    return false;
}

This is just an example for 200 OK and you might also want to check if the status code is some other in 2XX or in 3XX (redirection) class.

like image 120
pajaja Avatar answered Oct 31 '25 10:10

pajaja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!