1. Classes commonly used in Qt to parse HTTP
Some classes are provided in Qt to implement the high-level network protocols in the OSI 7-layer network model, such as HTTP, FTP, SNMP, etc. These related classes mainly include QNetworkRequest, QNetworkReply, and QNetworkAccessManager.
The QNetworkRequest class initiates a network protocol request through a URL address, and also saves the information of the network request. Currently, it supports downloading or uploading of HTTP, FTP, and partial file URLs.
The QNetworkAccessManager class is used to coordinate network operations. After QNetworkRequest sends a network request, the QNetworkAccessManager class is responsible for sending the network request and creating the network response.
The QNetworkReply class represents a response to a network request. A network response is created by QNetworkAccessManager after sending a network request. The signals finished(), readyRead() and downloadProgress() provided by QNetworkReply can monitor the network response and perform corresponding operations.
Note : QNetworkReply is a subclass of QIODevice, so QNetworkReply supports stream read and write functions, and also supports asynchronous or synchronous working modes.
Second, the application based on HTTP protocol in Qt
To develop HTTP-related applications, you need to add QT += network to the project file .pro
Introduction to HTTP
HTTP is the abbreviation of HyperText Transfer Protocol, a hypertext transfer protocol, which is a standard for request and response between the client and the server. The headers of the request and response messages are given in ASCII form; while the message content has A MIME-like format.
HTTP communication model
header file reference
#include <QHttpMultiPart>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QMetaObject>
#include <QEventLoop>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonArray>
#include <QFile>
Commonly used HTTP request methods
The two most commonly used methods for request-response between client and server are: GET and POST.
- GET - Requests data from the specified resource.
- POST - Submits data to be processed to the specified resource.
HTTP application example
1) Based on the HTTP protocol, it is used in Qt to request URL links to read Json or Xml lightweight strings
(1) get method
void HTTPClient::HttpGetRequest()
{ QNetworkRequest request1; QNetworkAccessManager manager; connect(&manager, &QNetworkAccessManager::finished, this, &HTTPClient::receiveHttpGetReply); request1.setUrl(QUrl("http://123.12.365.152/X SD?type" )); request1.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json;charset=utf-8")); QString sToken = "xxxxxxxxxxxxxxxxx"; QString tokenHeader = sToken; request1.setRawHeader("token", tokenHeader. toLocal8Bit()); QNetworkReply *reply = manager.get(request1); //get request header //Open the event loop until the request is completed 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 ) { //When the return code is 200, it proves that the request is successful if(rootObj.contains("result")) {
//Analyze data
}
result = 0;
}
else
{ //Request failure corresponding processing result = codeResult.toInt(); } } return result; }
post method:
void HTTPClient::PostHttpRequest()
{ QByteArray dataArray; //Get the corresponding parameter data dataArray.append("paramer1="); dataArray.append(paramer1.toUtf8()); dataArray.append("¶mer2="); dataArray .append(paramer2.toUtf8()); //http request QNetworkRequest request; QNetworkAccessManager manager; connect(&manager, &QNetworkAccessManager::finished, this, &HTTPClient::receiveHttpPostReply); request.setUrl(QUrl("http://192.168. 1.152/XSD")); XSD refers to URL interface name //request header token setting request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/x-www-form-urlencoded"));
QNetworkReply* reply = manager.post(request, dataArray); //post request header + transmitted data
//Open the event loop until the request is completed
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(jsonErr or.error != QJsonParseError: :NoError) { result = -1; } QJsonObject rootObject = jsonDoc.object(); QString codeResult = rootObject.value("code").toString(); if (codeResult.compare("200") == 0) { //When the return code is 200, it proves that the request is successful if(rootObject.contains("result")) { } result = 0;
}
else
{ //Request failure corresponding processing result = codeResult.toInt(); } return result; }
2) Based on the HTTP protocol, it is used for uploading or downloading files in Qt
(1) First, you can use QtCreate or Qtvs to create a window program, import the network module, and add relevant header files, such as
#include<QUrl>
#include<QFile>
#include<QProgressBar>
...
(2) Add private slot function declaration:
void httpFinished();
void httpReadyRead();
void updateDataReadProgress(qint64, qint64);
(3) Add private object definition:
QNetworkReply *reply;
QUrl url;
QFile *file;
Add ui->progressBar->hide() to the constructor in the .cpp file
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();
}