本文小编为大家详细介绍“Qt怎么实现HTTP的Get/Post请求”,内容详细,步骤清晰,细节处理妥当,希望这篇“Qt怎么实现HTTP的Get/Post请求”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
借助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管理、代理设置等功能。
QNetworkRequest提供了对本次网络请求的封装,在本示例中只是构造了一个最简单的requset,没有进行任何参数设置。QNetworkRequest提供了很多方法来对请求进行配置,比如我们可以使用QNetworkRequest::setHeader设置请求头等。
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->post(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(); }}
读到这里,这篇“Qt怎么实现HTTP的Get/Post请求”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注编程网行业资讯频道。