一、阻塞方式
#include
#include
#include
#include
#include
#include
#include
#include
#include
QString HttpHelper::httpRequestBlock(const QString contentType, const QString url)
{
static QMutex mutex;
QMutexLocker locker(&mutex);
QDateTime startTime = QDateTime::currentDateTime(); // 当前时间
//生成对应的网络请求
QNetworkRequest request;
request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentType)); // 设置Content-Type为application/json
request.setUrl(QUrl(url));
//发送Get请求
QNetworkAccessManager manager;
QNetworkReply *reply = manager.get(request);
QEventLoop eventLoop;
QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit()));
eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
//对请求的返回异常进行处理
if(reply->error() != QNetworkReply::NoError)
{
qDebug()<< reply->error();
delete reply;
return "";
}
//解析返回的Json结果
QByteArray replyData = reply->readAll();
QString res = QString(replyData);
delete reply;
QDateTime endTime = QDateTime::currentDateTime(); // 结束时间
qDebug()<<"http request time:"<< startTime.msecsTo(endTime); // 毫秒差值
return res;
}
二、非阻塞方式
#include
#include
#include
#include
#include
#include
#include
#include
#include
void HttpHelper::httpRequestNoBlockSlot(const QString contentType, const QString url, uint16_t timeout)
{
this->httpResult.clear();
this->networkAccessManager->setTransferTimeout(timeout);
//发送异步get请求
QNetworkRequest request;
request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentType)); // 设置Content-Type为application/json
request.setUrl(QUrl(url));
QNetworkReply *reply = this->networkAccessManager->get(request);
connect(reply, &QNetworkReply::finished,
[=]()
{
if(reply->error()!=QNetworkReply::NoError)
{
//处理中的错误信息
qDebug()<<"reply error:"<<reply->errorString();
qDebug()<<"status code:"<<reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
}
else
{
//请求方式
// qDebug()<<"operation:"<operation();
// //状态码
// qDebug()<<"status code:"<attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
// qDebug()<<"url:"<url();
// //qDebug()<<"raw header:"<rawHeaderList();
//获取响应信息
QByteArray replyData = reply->readAll();
this->httpResult = QString(replyData);
}
delete reply;
});
}