一、Qt中常用来解析HTTP的类
在Qt中提供了一些类用来实现OSI 7层网络模型中高层的网络协议,如HTTP、FTP、SNMP等,这些相关类主要有QNetworkRequest、QNetworkReply,QNetworkAccessManager。
QNetworkRequest类通过一个URl地址发起网络协议请求,也保存网络请求的信息,目前支持HTTP、FTP和局部文件URLs的下载或上传。
QNetworkAccessManager类用于协调网络操作。在QNetworkRequest发送一个网络请求后,QNetworkAccessManager类负责发送网络请求,创建网络响应。
QNetworkReply类表示网络请求的响应。由QNetworkAccessManager在发送一个网络请求后,创建一个网络响应。QNetworkReply提供的信号finished()、readyRead()和downloadProgress()可以监测网络响应的情况,执行相应操作。
说明:QNetworkReply是QIODevice的子类,所以QNetworkReply支持流读写功能,也支持异步或者同步工作模式。
二、基于HTTP协议在Qt中的应用
要开发HTTP相关应用,需要先在工程文件.pro中加入QT += network
HTTP简介
HTTP 是 HyperText Transfer Protocol的简称,一种超文本传输协议,它是客户端与服务端之间进行请求和应答的标准,请求和响应消息的头以ASCII形式给出;而消息内容则具有一个类似MIME的格式。
HTTP通信模型
头文件引用
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
常用的HTTP请求方式
在客户机和服务器之间进行请求-响应时,两种最常被用到的方法是:GET 和 POST。
HTTP应用示例
1)基于HTTP协议在Qt中用于请求URL链接读取Json或者Xml轻量字符串
(1)get方式
void HTTPClient::HttpGetRequest()
{
QNetworkRequest request1;
QNetworkAccessManager manager;
connect(&manager, &QNetworkAccessManager::finished, this, &HTTPClient::receiveHttpGetReply);
request1.setUrl(QUrl("http://123.12.365.152/XSD?type"));
request1.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json;charset=utf-8"));
QString sToken = "xxxxxxxxxxxxxxxx";
QString tokenHeader = sToken;
request1.setRawHeader("token", tokenHeader.toLocal8Bit());
QNetworkReply *reply = manager.get(request1); //get请求头
//开启事件循环,直到请求完成
QEventLoop loop;
connect(reply, &QNetworkReply::finished,&loop, &QEventLoop::quit);
loop.exec();
}
int HTTPClient::receiveHttpGetReply(QNetworkReply* reply)
{
int result;
QByteArray replyArray = reply->readAll();
QJsonParseError json_error;
QJsonDocument jsonDoc(QJsonDocument::fromJson(replyArray, &json_error));
if(json_error.error != QJsonParseError::NoError)
{
result = -1;
}
else
{
QJsonObject rootObject = jsonDoc.object();
QString codeResult = rootObject.value("code").toString();
if (codeResult.compare("200") == 0)
{
//返回代码为200的时候证明请求成功
if(rootObj.contains("result"))
{
//解析数据
}
result = 0;
}
else
{
//请求失败对对应的处理
result = codeResult.toInt();
}
}
return result;
}
post方式:
void HTTPClient::PostHttpRequest()
{
QByteArray dataArray; //获取对应的参数数据
dataArray.append("paramer1=");
dataArray.append(paramer1.toUtf8());
dataArray.append("¶mer2=");
dataArray.append(paramer2.toUtf8());
//http请求
QNetworkRequest request;
QNetworkAccessManager manager;
connect(&manager, &QNetworkAccessManager::finished, this, &HTTPClient::receiveHttpPostReply);
request.setUrl(QUrl("http://192.168.1.152/XSD")); XSD代指URL接口名称
//请求头token设置
request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/x-www-form-urlencoded"));
QNetworkReply* reply = manager.post(request, dataArray); //post请求头+传输的数据
//开启事件循环,直到请求完成
QEventLoop loop;
connect(reply,&QNetworkReply::finished,&loop,&QEventLoop::quit);
loop.exec();
}
int HTTPClient::receiveHttpPostReply(QNetworkReply* reply)
{
int result;
QByteArray replyArray = reply->readAll();
QJsonParseError jsonError;
QJsonDocument jsonDoc(QJsonDocument::fromJson(replyArray, &jsonError));
if(jsonError.error != QJsonParseError::NoError)
{
result = -1;
}
QJsonObject rootObject = jsonDoc.object();
QString codeResult = rootObject.value("code").toString();
if (codeResult.compare("200") == 0)
{
//返回代码为200的时候证明请求成功
if(rootObject.contains("result"))
{
}
result = 0;
}
else
{
//请求失败对对应的处理
result = codeResult.toInt();
}
return result;
}
2)基于HTTP协议在Qt中用于文件的上传或者下载
(1)首先可以利用QtCreate或者Qtvs创建一个窗口程序,在引入network模块,并加入相关头文件,如
#include
#include
#include
...
(2)添加私有槽函数声明:
void httpFinished();
void httpReadyRead();
void updateDataReadProgress(qint64, qint64);
(3)添加私有对象定义:
QNetworkReply *reply;
QUrl url;
QFile *file;
在.cpp文件中构造函数中添加ui->progressBar->hide();
void HTTPClient::startRequest(QUrl url)
{
reply = manager->get(QNetworkRequest(url));
connect(reply, SIGNAL(readyRead()), this, SLOT(httpReadyRead()));
connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(updateDataReadProgress(qint64, qint64)));
connect(reply, SIGNAL(finished()), this, SLOT(httpFinished()));
}
void HTTPClient::httpReadyRead()
{
if(file) file->write(reply->write(readAll()));
}
void HTTPClient::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
ui->progressBar->setMaximum(totalBytes);
ui->progressBar->setValue(bytesRead);
}
void HTTPClient::httpFinished()
{
ui->progressBar->hide();
file->flush();
file->close();
reply->deleteLater();
reply = NULL;
delete file;
file = NULL;
}
void HTTPClient::on_downloadbtn_clicked()()
{
url = ui->fileEdit->text();
QFileInfo info(url.path());
QString fileName(info.fileName());
file = new QFile(fileName);
if(!file->open(QIODevice::WriteOnly))
{
qDebug()<<"file open error";
delete file;
file = NULL;
return;
}
startRequest(url);
ui->progressBar->setValue(0);
ui->progressBar->show();
}