Search code examples
c++qtmime-typesqwebkitqwebpage

QWebPage, getting the mime type


I am wondering how I can get the mime-type of the current page using a QWebPage. Also, if possible, I would like to be able to do this using the HEAD request so I know not to download the whole page if it's not the correct mime-type. Any ideas?


Solution

  • It is possible. You will want to use QNetworkAccessManager, QNetworkRequest, and QNetworkReply classes.

    Here's an (untested) example, but should get you started with retrieving the mime-type of a page using a HEAD request:

    class TestClass: public QObject
    {
        Q_OBJECT
    public:
        TestClass();
        void run();
    
    public slots:
        void ready(QNetworkReply * response);
    
    protected:
        QNetworkAccessManager * manager;
    };
    
    
    TestClass::TestClass()
    {
        manager = new QNetworkAccessManager(this);
    
        this->connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ready(QNetworkReply*)));
    }
    
    void TestClass::run()
    {
        QUrl url("http://www.widefido.com/");
    
        manager->head(QNetworkRequest(url));
    }
    
    void TestClass::ready(QNetworkReply * response)
    {
        QVariant contentMimeType = response->header(QNetworkRequest::ContentTypeHeader);
    
        qDebug() << contentMimeType;
    }
    

    NOTE: If the server does not send back a ContentType header, your QVariant will be invalid. So, before using contentMimeType, make sure you check if it is valid first. Then you can convert to a QString for checking against your list of valid mime-types.

    NOTE: QNetworkRequests are asynchronous, so you'll have to implement a signal-slot relationship for getting the value out of the QNetworkReploy. You can also have a look in QxtSignalWaiter for doing it inline.