1. 程式人生 > >Qt使用network模組進行http請求時獲取response中的http狀態碼

Qt使用network模組進行http請求時獲取response中的http狀態碼

http請求獲取response中的http狀態碼

最近轉行學習Qt,不得不說,還是Java寫得舒服。 回到正題,在使用Qt時,可能會使用network模組來進行網路操作,比如tcp、http請求,我將在下文講述如何通過Qt進行http請求以及處理響應的相關操作。

使用QNetworkAccessManager

Qt通過QNetworkAccessManager來管理網路請求,Qt提供了QNetworkCookieJar來管理Cookie,當然你可以通過手工管理request的header來管理Cookie,不過相對麻煩。

    QNetworkAccessManager *manager = new QNetworkAccessManager;
    
    // 添加了QNetworkCookieJar
    // 可以自己寫個類繼承QNetworkCookieJar,呼叫QNetworkCookieJar的allCookies函式來獲取cookie列表
    manager->setCookieJar(&cookieJar);

由於QNetworkAccessManager的請求回傳使用的是非同步傳輸,所以可以用Qt訊號槽機制來進行response的獲取。

    // 這裡使用QEventLoop來進行迴圈等待
    QEventLoop *loop = new QEventLoop;
    connect(manager, SIGNAL(finished(QNetworkReply*)), loop, SLOT(quit()));
    QNetworkRequest request(QUrl("your uri"));
    QNetworkReply *reply = manager->get(request);
    loop->exec();

可以通過QNetworkReply的readAll()成員函式來獲取返回的具體內容:

    QByteArray bytes = reply->readAll();
    qDebug() << bytes;

獲取http狀態碼

在獲得伺服器的響應後,程式編寫者可能需要獲得響應的http狀態碼,具體步驟如下:

    // QNetworkReply
    // attribute函式返回QVariant物件,使用value<T>()函式返回進行向下轉型
    qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).value<int>();

關於QNetworkReply::attribute

官方文件這麼表述改方法:

QVariant QNetworkReply::attribute(QNetworkRequest::Attribute code) const Returns the attribute associated with the code code. If the attribute has not been set, it returns an invalid QVariant (type QMetaType::UnknownType). You can expect the default values listed in QNetworkRequest::Attribute to be applied to the values returned by this function.

意思是attribute函式返回code程式碼對應的引數。如果引數沒有被設定,函式將返回無效的QVariant物件(Invalid QVariant),你能使用QNetworkRequest::Attribute中提供的引數當錯code來呼叫attribute函式並返回你需要的值。常用的引數有:

  1. QNetworkRequest::RedirectionTargetAttribute(返回重定向地址)
  2. QNetworkRequest::HttpStatusCodeAttribute(返回ht