get请求无参,只有网络地址,这里以请求城市天气信息为例,发起get请求,返回天气json格式数据
头文件
private:
void queryWeather();//查询
public slots:
void replyFinished(QNetworkReply *reply);//刷新的槽
private:
QString cityName;
QNetworkAccessManager *manager; //请求句柄
QString allinfo; //所有信息
//以下皆是当天,未来几天的数据框通过获取日期的数据列表
QString date;//当前日期
QString fengli; //风力
QString wendu; //温度
QString currentwendu;//当前温度
QString weather_type; //天气类型
QString ganmao;//对于感冒提示
bool isGetData=false;//是否成功获取数据
源文件
manager = new QNetworkAccessManager(this); //新建QNetworkAccessManager对象
connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));//关联信号和槽
//查询天气
void Weather::queryWeather()
{
cityName = "南京";
char quest_array[256]="http://wthrcdn.etouch.cn/weather_mini?city=";
QNetworkRequest quest;
sprintf(quest_array,"%s%s",quest_array,cityName.toUtf8().data());
quest.setUrl(QUrl(quest_array));
quest.setHeader(QNetworkRequest::UserAgentHeader,"RT-Thread ART");
/*发送get网络请求*/
manager->get(quest);
}
//信号槽接收网络响应,处理接收到的数据
void Weather::replyFinished(QNetworkReply *reply)
{
this->isGetData=false;
allinfo = reply->readAll();
QJsonParseError err;
QJsonDocument json_recv = QJsonDocument::fromJson(allinfo.toUtf8(),&err);//解析json对象
if(!json_recv.isNull())
{
QJsonObject object = json_recv.object();
if(object.contains("data"))
{
QJsonValue value = object.value("data"); // 获取指定 key 对应的 value
if(value.isObject())
{
QJsonObject object_data = value.toObject();
this->cityName=object_data.value("city").toString();
this->currentwendu=object_data.value("wendu").toString();
this->ganmao=object_data.value("ganmao").toString();
if(object_data.contains("forecast"))
{
QJsonValue value = object_data.value("forecast");
if(value.isArray())
{
QJsonObject today_weather = value.toArray().at(0).toObject();
weather_type = today_weather.value("type").toString();
date = today_weather.value("date").toString();
QString low = today_weather.value("low").toString();
QString high = today_weather.value("high").toString();
wendu = low.mid(low.length()-3,4) +"-"+ high.mid(high.length()-3,4);
QString strength = today_weather.value("fengli").toString();
strength.remove(0,8);
strength.remove(strength.length()-2,2);
fengli = today_weather.value("fengxiang").toString() + strength;
this->isGetData=true;
}
}
}
}
}else
{
qDebug()<<"json_recv is NULL or is not a object !!";
}
reply->deleteLater(); //销毁请求对象
if(isGetData)
{
qDebug()<<QString::fromLocal8Bit("获取天气成功");
}
else
{
qDebug()<<QString::fromLocal8Bit("获取天气失败");
}
}
qt发起post请求,带网络地址和参数,参数一般为json格式,转QByteArray
//发起post请求
void MainWindow::postHttpRequest()
{
QNetworkRequest request;
QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
QObject::connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
request.setUrl(QUrl::fromUserInput(" http://192.168.1.102:2345/notice?num=4567"));
QJsonObject obj1;
QJsonObject object;
object.insert("station","业务受理员");
object.insert("name","王晨");
object.insert("number","0001");
object.insert("pic","http://192.168.1.15:8080/8.jpg");
object.insert("orderNum","A123456789B");
obj1.insert("data",object);
obj1.insert("status","2");
QByteArray byte_array = QJsonDocument(obj1).toJson();
qDebug()<< "user info " << obj1;
QNetworkReply* reply = naManager->post(request,byte_array);//发起post请求
}
//接收网络响应槽函数
void MainWindow::requestFinished(QNetworkReply *reply)
{
QString loginResultJson;
QByteArray bytes = reply->readAll();
// 获取http状态码
QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if(statusCode.isValid())
{
qDebug() << "status code=" << statusCode.toInt();
}
QNetworkReply::NetworkError err = reply->error();
if(err != QNetworkReply::NoError)
{
qDebug() << "Failed: " << reply->errorString();
}
else
{
// 获取返回内容
qDebug() << "loginResultJson is " << QString::fromStdString(bytes.toStdString());
loginResultJson = QString::fromStdString(bytes.toStdString());
//处理返回数据
}
}
GET和POST方式均可使用,收发同步,并增加了等待接收超时处理。
/**
* @brief http发送和接收接口
* @param strUrl HTTP网络URL
* @param thod HTTP方法,GET或POST
* @param strInput 发送的数据
* @param strMessage http返回的错误信息
* @param strResult http接收响应
*/
void SendAndGetText(QString strUrl, QString thod, QString strInput, QString &strMessage, QString &strResult)
{
QNetworkRequest oNetRequest;
oNetRequest.setUrl(QUrl(strUrl));
QNetworkAccessManager oNetAccessManager;
QNetworkReply* oNetReply = nullptr;
QByteArray inputTmp;
if (thod == "POST")
{
oNetRequest.setRawHeader("Content-Type", "application/octet-stream");
if(REST_TOKEN == globalHs.transType)
oNetRequest.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
oNetReply = oNetAccessManager.post(oNetRequest, strInput.toLocal8Bit());
//oNetReply = oNetAccessManager.post(oNetRequest, content);
}
else if (thod == "GET" )
{
oNetReply = oNetAccessManager.get(oNetRequest);
}
// 添加超时处理,10s超时
QEventLoop eventloop;
connect(oNetReply, SIGNAL(finished()), &eventloop, SLOT(quit()));
QTimer::singleShot(10000, &eventloop, &QEventLoop::quit);
eventloop.exec();
QByteArray array;
if(oNetReply->isFinished())
{
if(oNetReply->error() == QNetworkReply::NoError)//正常结束,读取响应数据
{
strResult = oNetReply->readAll();
}
else//异常结束,比如不存在的http服务器,错误信息:Connection refused
{
}
}
else//超时,错误信息:Operation canceled
{
disconnect(oNetReply, &QNetworkReply::finished, &eventloop, &QEventLoop::quit);
oNetReply->abort();
qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<" timeout";
}
QNetworkReply::NetworkError e = oNetReply->error();
if (e)
{
strMessage = oNetReply->errorString();
}
oNetReply->deleteLater();
}
///调用示例
QString url = "";//http后台地址url
QString sendMsg = "";//http发送数据组包
QString strMessage = "";//错误信息
QString strResult = "";//http响应
QString thod = "POST";//POST或GET
SendAndGetText(url,thod,sendMsg,strMessage,strResult);
if(strMessage.isEmpty())///HTTP正常响应
{
qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<"接收数据 "<<strResult;
}
else///HTTP通信异常
{
qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<"错误信息 "<<strMessage;
}
/**
* @brief 获取网络地址图片
* @param url 图片网络地址,例如http://106.15.226.233/slImg/bg1.png
* @return QPixmap图片
*/
QPixmap HttpGetPic::GainUrlImage(QString url)
{
QUrl turl(url);
QNetworkAccessManager manager;
QEventLoop loop;
QNetworkReply *reply = manager.get(QNetworkRequest(turl));
//请求结束并下载完成后,退出子事件循环
connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
//开启子事件循环
loop.exec();
QByteArray jpegData = reply->readAll();
QPixmap pixmap;
if(!pixmap.loadFromData(jpegData))
{
CLOG_ERROR(QString("网络地址获取图片失败,URL=%1").arg(url).toUtf8().data());
}
return pixmap;
}