轉載自:https://www.jb51.net/program/3074287bh.htm
使用QT進行應用開發時,有時候需要進行客戶端和服務端的網路通訊,本文主要介紹了QT使用Http協議通訊的實現示例,具有一定的參考價值,感興趣的可以瞭解一下
介紹
使用QT進行應用開發時,有時候需要進行客戶端和服務端的網路通訊,網路通訊常用的一種協議就是http協議。QT對http協議進行了封裝,下面將介紹兩種http通訊方式的使用。
在使用http時需要在pro檔案中新增對應的模組。
1
|
QT += network |
http主要兩種通訊方式為get和post兩種
1.多個獨立引數GET請求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
int NormalGetRequest(QString paramer1, QString paramer2) { //生成對應的網路請求 QNetworkRequest request; QString scheme = "http" ; QString serverAddr = "192.168.0.1" ; QString port = "80" ; QString requestHeader = scheme + QString( "://" ) + serverAddr + QString( ":" ) + port; QString fullRequest = requestHeader + QString( "/api/vi/user/getrequest?paramer1=%1¶mer2=%2" ).arg(paramer1).arg(paramer2); request.setUrl(QUrl(fullRequest)); //傳送Get請求 QNetworkAccessManager manager; QNetworkReply *reply = manager.get(request); QEventLoop eventLoop; QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit())); eventLoop.exec(QEventLoop::ExcludeUserInputEvents); //對請求的返回異常進行處理 if (reply->error() != QNetworkReply::NoError) { return reply->error(); } //解析返回的Json結果 QByteArray replyData = reply->readAll(); QJsonParseError json_error; QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error)); if (json_error.error != QJsonParseError::NoError) { return -1; } QJsonObject rootObj = jsonDoc.object(); QString codeStr = rootObj.value( "code" ).toString(); if (codeStr.compare( "200" ) == 0) { //返回程式碼為200的時候證明請求成功對包含的結構資料進行處理 if (rootObj.contains( "result" )) { } return 0; } else { //請求失敗對對應的處理 return codeStr.toInt(); } } |
2.引數陣列GET請求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
int GetRequestWithArray(QVector<QString> m_filePathVector) { QJsonArray array; for ( int index=0; index<m_filePathVector.size(); ++index) { QJsonObject object; object.insert( "index" ,QString::number(index)); object.insert( "path" ,m_filePathVector.at(index)); array.append(object); } QJsonDocument document; document.setArray(array); QString arrayString = document.toJson(QJsonDocument::Compact); //生成對應的網路請求 QNetworkRequest request; QString scheme = "http" ; QString serverAddr = "192.168.0.1" ; QString port = "80" ; QString requestHeader = scheme + QString( "://" ) + serverAddr + QString( ":" ) + port; QString fullRequest = requestHeader + QString( "/api/vi/user/getarray?paramers=%1" ).arg(arrayString); request.setUrl(QUrl(fullRequest)); //獲取錯誤 QNetworkAccessManager manager; QNetworkReply *reply = manager.get(request); QEventLoop eventLoop; QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit())); eventLoop.exec(QEventLoop::ExcludeUserInputEvents); if (reply->error() != QNetworkReply::NoError) { return reply->error(); } //解析返回的Json結果 QByteArray replyData = reply->readAll(); QJsonParseError json_error; QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error)); if (json_error.error != QJsonParseError::NoError) { return -1; } QJsonObject rootObj = jsonDoc.object(); QString codeStr = rootObj.value( "code" ).toString(); if (codeStr.compare( "200" ) == 0) { //返回程式碼為200的時候證明請求成功對包含的結構資料進行處理 if (rootObj.contains( "result" )) { } return 0; } else { //請求失敗對對應的處理 return codeStr.toInt(); } } |
3.上傳引數資料POST請求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
int NormalPostRequest(QString paramer1, QString paramer2) { //生成對應的網址請求 QNetworkRequest request; QString scheme = "http" ; QString serverAddr = "192.168.0.1" ; QString port = "80" ; QString requestHeader = scheme + QString( "://" ) + serverAddr + QString( ":" ) + port; QString fullRequest = requestHeader + "/api/v1/user/postrequest" ; request.setUrl(QUrl(fullRequest)); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded" ); //獲取對應的引數資料 QByteArray data; data.append( "paramer1=" ); data.append(paramer1.toUtf8()); data.append( "¶mer2=" ); data.append(paramer2.toUtf8()); //傳送請求 QNetworkAccessManager manager; QNetworkReply *reply = manager.post(request,data); QEventLoop eventLoop; QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit())); eventLoop.exec(QEventLoop::ExcludeUserInputEvents); if (reply->error() != QNetworkReply::NoError) { return reply->error(); } //解析返回的Json結果 QByteArray replyData = reply->readAll(); QJsonParseError json_error; QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error)); if (json_error.error != QJsonParseError::NoError) { return -1; } QJsonObject rootObj = jsonDoc.object(); QString codeStr = rootObj.value( "code" ).toString(); if (codeStr.compare( "200" ) == 0) { //返回程式碼為200的時候證明請求成功對包含的結構資料進行處理 if (rootObj.contains( "result" )) { } return 0; } else { //請求失敗對對應的處理 return codeStr.toInt(); } } |
4.上傳引數和檔案POST請求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
int PostRequestWithFile(QString paramer1, QString paramer2,QString filePath) { //生成對應的網址請求 QFileInfo fileInfo(filePath); QString fileName =fileInfo.fileName(); QFile* inputFile = new QFile(filePath); inputFile->open(QIODevice::ReadOnly); //multipart請求 QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); //檔案塊 QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QString( "form-data; name=\"uploadfile\";filename=\"%1\"" ).arg(fileName))); filePart.setBodyDevice(inputFile); inputFile->setParent(multiPart); multiPart->append(filePart); QHttpPart paramer1Part; paramer1Part.setHeader(QNetworkRequest::ContentDispositionHeader,QVariant( "form-data; name=\"paramer1\"" )); paramer1Part.setBody(paramer1.toUtf8()); multiPart->append(paramer1Part); QHttpPart paramer2Part; paramer2Part.setHeader(QNetworkRequest::ContentDispositionHeader,QVariant( "form-data; name=\"paramer2\"" )); paramer2Part.setBody(paramer2.toUtf8()); multiPart->append(paramer2Part); //生成對應的網址請求 QNetworkRequest request; QString scheme = "http" ; QString serverAddr = "192.168.0.1" ; QString port = "80" ; QString requestHeader = scheme + QString( "://" ) + serverAddr + QString( ":" ) + port; QString fullRequest = requestHeader + "/api/v1/user/postrequestwithfile" ; request.setUrl(QUrl(fullRequest)); //傳送請求 QNetworkAccessManager manager; QNetworkReply *reply = manager.post(request,multiPart); multiPart->setParent(reply); QEventLoop eventLoop; QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)),&eventLoop, SLOT(quit())); eventLoop.exec(QEventLoop::ExcludeUserInputEvents); if (reply->error() != QNetworkReply::NoError) { return reply->error(); } //解析返回的Json結果 QByteArray replyData = reply->readAll(); QJsonParseError json_error; QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error)); if (json_error.error != QJsonParseError::NoError) { return -1; } QJsonObject rootObj = jsonDoc.object(); QString codeStr = rootObj.value( "code" ).toString(); if (codeStr.compare( "200" ) == 0) { //返回程式碼為200的時候證明請求成功對包含的結構資料進行處理 if (rootObj.contains( "result" )) { } return 0; } else { //請求失敗對對應的處理 return codeStr.toInt(); } } |
5.下載檔案GET請求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
int DownloadFileFromWeb(QString fileUrl,QString&fileSavePath) { QNetworkRequest request; QUrl url(fileUrl); QFileInfo fileInfo(url.path()); QString fileName = fileInfo.fileName(); QNetworkAccessManager *accessManager= new QNetworkAccessManager(); request.setUrl(url); QNetworkReply *reply = accessManager->get(request); QEventLoop loop; QObject::connect(accessManager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit())); //如果需要下載進度需要關聯對應的訊號 //connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(LoadProgress(qint64, qint64))); loop.exec(QEventLoop::ExcludeUserInputEvents); //獲取下載返回值 QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); if (statusCode.toInt() != 200) { return -1; } //儲存下載的檔案 QFile file(fileSavePath); if (!file.open(QIODevice::WriteOnly)) { return -2; } file.write(reply->readAll()); file.close(); return 0; } |
到此這篇關於QT使用Http協議通訊的實現示例的文章就介紹到這了,更多相關QT Http協議通訊內容請搜尋指令碼之家以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援指令碼之家!
擴充套件文章:
【Qt入門第32篇】 網路(二)HTTP:https://blog.csdn.net/hw5230/article/details/128254099