借助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一样):文章来源:https://www.toymoban.com/news/detail-722433.html
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开发学习资料包、技术视频,内容包括(C++语言基础,C++设计模式,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击莬费领取↓↓文章来源地址https://www.toymoban.com/news/detail-722433.html
到了这里,关于Qt实现HTTP的Get/Post请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!