c++qtqnetworkaccessmanagerqnetworkreplyqnetworkrequest

How to get the status of an URL?


I am using Qt and what I should do is given a QString containing my URL, before opening the page, I want to know if this is reachable.

I read the documentation of QNetworkReply and I saw that there are different codes for the different types of error (eg: the remote content was not found at the server -> code 203).

The question is: starting from my QString, how can I get those code values?


Solution

  • How to know if this is reachable, before opening the page?

    It is not something you could know in advance, but a trial and error:

    1. Make the request
    2. Check for errors
    3. Get the error code

    How can I do this?

    Let's take the example from the documentation:

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QNetworkRequest request;
    
    request.setUrl(QUrl("http://put.your-url.here"));
    
    QNetworkReply *reply = manager->get(request);
    
    connect(reply, &QIODevice::readyRead, this, &MyClass::slotReadyRead);
    connect(reply, &QNetworkReply::errorOccurred,
            this, &MyClass::slotError);
    connect(reply, &QNetworkReply::sslErrors,
            this, &MyClass::slotSslErrors);
    

    Now in the implementation of MyClass::slotError, write:

    qDebug() << static_cast<QNetworkReply *>(sender())->error();
    

    This should print the error code, if any.