【Qt-11】http通信(Get同步收发)

【Qt-9】HTTP请求(post方式)_WXG1011的博客-CSDN博客

【QT-6】QWebApp服务器搭建及使用_qtwebapp_WXG1011的博客-CSDN博客

写在前面:在上面两篇博文的基础上,继续迭代功能。

上面两篇博客已实现QWebApp服务器搭建、http通信发送请求及接收响应数据等功能。下面实现多层http通信。

【Qt-11】http通信(Get同步收发)_第1张图片

 采用异步接收响应数据时一直报无法读取内存的错误,故采用同步接收响应数据的方式。这里http请求方式采用Get形式。

伪代码如下:

void MeasurementController::PostRequestM(QString url)
{
	//http请求
	QNetworkRequest request1;
	QNetworkAccessManager nam;
	//connect(&nam, &QNetworkAccessManager::finished, this, &MeasurementController::receivePostReply);

	qDebug() << "request data!";
	request1.setUrl(QUrl(url));    //实时请求网址
	qDebug() << "request end!";
	//request1.setUrl(QUrl("http://10.1.101.195:8085/measurement"));    //实时请求网址

	//请求头token设置
	/*request1.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json;charset=utf-8"));
	QString token = "xxxxxxxxxxxxxxxxxxxxxxxx";
	QString token_headerData = token;
	request1.setRawHeader("token", token_headerData.toLocal8Bit());*/

	//QNetworkReply* reply = nam.post(request1, byte_array);        //post请求头+传输的数据
	QNetworkReply* reply = nam.get(request1);        //get请求头


	
	//开启事件循环,直到请求完成
	QEventLoop loop;
	connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
	//connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
	loop.exec();

	QString strMessage = "";//错误信息
	QString strResult = "";//http响应
	QByteArray array;
	if (reply->isFinished())
	{
		if (reply->error() == QNetworkReply::NoError)//正常结束,读取响应数据
		{
			strResult = reply->readAll();
			qDebug() << strResult;
			res = strResult.toUtf8();
		}
		else//异常结束,比如不存在的http服务器,错误信息:Connection refused
		{
		}
	}
	else//超时,错误信息:Operation canceled
	{
		disconnect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
		reply->abort();
		qDebug() << "[" << __FILE__ << "]" << __LINE__ << __FUNCTION__ << " timeout";
	}

	QNetworkReply::NetworkError e = reply->error();
	if (e)
	{
		strMessage = reply->errorString();
	}
	reply->deleteLater();
}

 参考链接 Qt发起http请求,get和post方式,并接收响应数据_qt发送http请求_架相的博客-CSDN博客

你可能感兴趣的:(http,网络协议,网络)