QNetworkAccessManager之http的同步请求

QByteArray HttpUtil::getData(QNetworkRequest request /*= QNetworkRequest()*/, const QByteArray & data /*= QByteArray()*/)
{
	m_networkReply = m_networkAccessManager->get(request);
	connect(m_networkAccessManager, &QNetworkAccessManager::sslErrors,
		this, &HttpUtil::onSslErrors);

	QEventLoop eventLoop;
	connect(m_networkReply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
	eventLoop.exec();
	QVariant httpStatusCode =
		m_networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
	QVariant redirectionTargetUrl =
		m_networkReply->attribute(QNetworkRequest::RedirectionTargetAttribute);
	qDebug() << "m_networkReply->error()" << m_networkReply->error();

	if (m_networkReply->error() == QNetworkReply::NoError)
	{
		QString rlt;

		typedef QPair<QByteArray, QByteArray> RawHeaderPair;
		QList<RawHeaderPair> rawHeaderPair = m_networkReply->rawHeaderPairs();
		int totlalLength = m_networkReply->rawHeader("Content-Length").toInt();

		QByteArray  fileName = m_networkReply->rawHeader("Content-Disposition");

		QString stringFileName = QString::fromUtf8(fileName);

		qDebug() << "stringFileName###:" << stringFileName;
		int reciveLength = 0;
		while (true)
		{
			QByteArray byteArray = m_networkReply->readAll();
			QString rlt = QString::fromUtf8(byteArray);
			qDebug() << "rlt###:" << rlt;
			reciveLength += byteArray.count();

			bool isFinish = m_networkReply->isFinished();
			qDebug() << "isFinish#:" << isFinish;

			if (m_networkReply->isFinished())
			{
				qDebug() << QStringLiteral("下载数据完成的。");
				return byteArray;
			}
			if (totlalLength == reciveLength)
			{
				qDebug() << "length == reciveLength:";
				qDebug() << QStringLiteral("下载数据完成的。");
				return byteArray;
			}
		}
		m_networkReply->deleteLater();
	}
	return QByteArray();
}

 

发布了43 篇原创文章 · 获赞 2 · 访问量 2万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览