借助Qt的NetWork模块,可以轻松的实现HTTP的Get/Post请求,而不需要再次引用像libcurl这样的第三方库。
当然,Qt的NetWork模块提供的功能远远不只是HTTP方面的。

<>头文件
#include <QNetworkRequest> #include <QNetworkReply> #include
<QNetworkAccessManager>
另外,使用Qt网络模块还需要引用Qt5Network.lib库。

<>Get

先构造一个QNetworkAccessManager对象,QNetworkAccessManager对象提供了发送QNetworkRequest网络请求和接收
QNetworkReply网络回复的功能。

QNetworkAccessManager还提供了缓存和Cookie管理、代理设置等功能。详见:
https://doc.qt.io/qt-5/qnetworkaccessmanager.html
<https://doc.qt.io/qt-5/qnetworkaccessmanager.html>

QNetworkRequest提供了对本次网络请求的封装,在本示例中只是构造了一个最简单的requset,没有进行任何参数设置。QNetworkRequest
提供了很多方法来对请求进行配置,比如我们可以使用QNetworkRequest::setHeader设置请求头等。详见:
https://doc.qt.io/qt-5/qnetworkrequest.html
<https://doc.qt.io/qt-5/qnetworkrequest.html>
void QtGuiApplication::onBtnGetClicked() { QNetworkRequest request;
QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
QMetaObject::Connection connRet = QObject::connect(naManager,
SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
Q_ASSERT(connRet); request.setUrl(QUrl("https://www.baidu.com"));
QNetworkReply* reply = naManager->get(request); }
请求是异步的,当请求完成之后,会调用void requestFinished(QNetworkReply* reply);槽函数:
void QtGuiApplication::requestFinished(QNetworkReply* reply) { // 获取http状态码
QVariant statusCode =
reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if(statusCode.isValid()) qDebug() << "status code=" << statusCode.toInt();
QVariant reason =
reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
if(reason.isValid()) qDebug() << "reason=" << reason.toString();
QNetworkReply::NetworkError err = reply->error(); if(err !=
QNetworkReply::NoError) { qDebug() << "Failed: " << reply->errorString(); }
else { // 获取返回内容 qDebug() << reply->readAll(); } }
<>Post
void QtGuiApplication::onBtnPushClicked() { QNetworkRequest request;
QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
QMetaObject::Connection connRet = QObject::connect(naManager,
SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
Q_ASSERT(connRet); request.setUrl(QUrl("https://www.baidu.com")); QString
testData = "test"; QNetworkReply* reply = naManager->put(request,
testData.toUtf8()); }
同样,请求也是异步的,当请求完成之后,会调用void requestFinished(QNetworkReply* reply);槽函数(和Get一样):
void QtGuiApplication::requestFinished(QNetworkReply* reply) { // 获取http状态码
QVariant statusCode =
reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if(statusCode.isValid()) qDebug() << "status code=" << statusCode.toInt();
QVariant reason =
reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
if(reason.isValid()) qDebug() << "reason=" << reason.toString();
QNetworkReply::NetworkError err = reply->error(); if(err !=
QNetworkReply::NoError) { qDebug() << "Failed: " << reply->errorString(); }
else { // 获取返回内容 qDebug() << reply->readAll(); } }