原文地址 blog.csdn.net
在使用Qt框架进行应用开发的过程中,很多时候需要进行客户端与服务端的网络通信,这时候就需要Qt的internet模块。而网络通信中最常用的协议就是http协议,Qt对http协议的调用进行了封装,使用非常方便。这里对常用的http请求demo做一下总结,方便大家参考。
在使用internet模块时需要在pro文件中添加对应的模块。
QT += network
Qt中使用Http协议与服务端通信的请求主要分为GET和POST,GET是从指定的资源请求数据,而POST是向指定的资源提交要被处理的数据。
常用的请求类型包括五类:
1.多个独立参数GET请求
2.参数数组GET请求
3.上传参数数据POST请求
4.上传参数和文件POST请求
5.下载文件GET请求
下面通过简单的Demo描述五种请求的调用方式。
1.多个独立参数GET请求
`
1. int NormalGetRequest(QString paramer1, QString paramer2)
2. {
3. //生成对应的网络请求
4. QNetworkRequest request;
5. QString scheme = "http";
6. QString serverAddr = "192.168.0.1";
7. QString port = "80";
8. QString requestHeader = scheme + QString("://") + serverAddr + QString(":") + port;
9. QString fullRequest = requestHeader + QString("/api/vi/user/getrequest?paramer1=%1¶mer2=%2").arg(paramer1).arg(paramer2);
10. request.setUrl(QUrl(fullRequest));
12. //发送Get请求
13. QNetworkAccessManager manager;
14. QNetworkReply *reply = manager.get(request);
15. QEventLoop eventLoop;
16. QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit()));
17. eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
19. //对请求的返回异常进行处理
20. if(reply->error() != QNetworkReply::NoError)
21. {
22. return reply->error();
23. }
25. //解析返回的Json结果
26. QByteArray replyData = reply->readAll();
27. QJsonParseError json_error;
28. QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
29. if(json_error.error != QJsonParseError::NoError)
30. {
31. return -1;
32. }
33. QJsonObject rootObj = jsonDoc.object();
34. QString codeStr = rootObj.value("code").toString();
35. if (codeStr.compare("200") == 0)
36. {
37. //返回代码为200的时候证明请求成功对包含的结构数据进行处理
38. if(rootObj.contains("result"))
39. {
41. }
42. return 0;
43. }
44. else
45. {
46. //请求失败对对应的处理
47. return codeStr.toInt();
48. }
49. }
`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
2.参数数组GET请求
`
1. int GetRequestWithArray(QVector<QString> m_filePathVector)
2. {
3. QJsonArray array;
4. for(int index=0; index<m_filePathVector.size(); ++index)
5. {
6. QJsonObject object;
7. object.insert("index",QString::number(index));
8. object.insert("path",m_filePathVector.at(index));
9. array.append(object);
10. }
12. QJsonDocument document;
13. document.setArray(array);
14. QString arrayString = document.toJson(QJsonDocument::Compact);
16. //生成对应的网络请求
17. QNetworkRequest request;
18. QString scheme = "http";
19. QString serverAddr = "192.168.0.1";
20. QString port = "80";
21. QString requestHeader = scheme + QString("://") + serverAddr + QString(":") + port;
22. QString fullRequest = requestHeader + QString("/api/vi/user/getarray?paramers=%1").arg(arrayString);
23. request.setUrl(QUrl(fullRequest));
25. //获取错误
26. QNetworkAccessManager manager;
27. QNetworkReply *reply = manager.get(request);
28. QEventLoop eventLoop;
29. QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit()));
30. eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
31. if(reply->error() != QNetworkReply::NoError)
32. {
33. return reply->error();
34. }
36. //解析返回的Json结果
37. QByteArray replyData = reply->readAll();
38. QJsonParseError json_error;
39. QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
40. if(json_error.error != QJsonParseError::NoError)
41. {
42. return -1;
43. }
44. QJsonObject rootObj = jsonDoc.object();
45. QString codeStr = rootObj.value("code").toString();
46. if (codeStr.compare("200") == 0)
47. {
48. //返回代码为200的时候证明请求成功对包含的结构数据进行处理
49. if(rootObj.contains("result"))
50. {
52. }
53. return 0;
54. }
55. else
56. {
57. //请求失败对对应的处理
58. return codeStr.toInt();
59. }
60. }
`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
3.上传参数数据POST请求
`
1. int NormalPostRequest(QString paramer1, QString paramer2)
2. {
3. //生成对应的网址请求
4. QNetworkRequest request;
5. QString scheme = "http";
6. QString serverAddr = "192.168.0.1";
7. QString port = "80";
8. QString requestHeader = scheme + QString("://") + serverAddr + QString(":") + port;
9. QString fullRequest = requestHeader + "/api/v1/user/postrequest";
10. request.setUrl(QUrl(fullRequest));
11. request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
13. //获取对应的参数数据
14. QByteArray data;
15. data.append("paramer1=");
16. data.append(paramer1.toUtf8());
17. data.append("¶mer2=");
18. data.append(paramer2.toUtf8());
20. //发送请求
21. QNetworkAccessManager manager;
22. QNetworkReply *reply = manager.post(request,data);
23. QEventLoop eventLoop;
24. QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit()));
25. eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
26. if(reply->error() != QNetworkReply::NoError)
27. {
28. return reply->error();
29. }
32. //解析返回的Json结果
33. QByteArray replyData = reply->readAll();
34. QJsonParseError json_error;
35. QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
36. if(json_error.error != QJsonParseError::NoError)
37. {
38. return -1;
39. }
40. QJsonObject rootObj = jsonDoc.object();
41. QString codeStr = rootObj.value("code").toString();
42. if (codeStr.compare("200") == 0)
43. {
44. //返回代码为200的时候证明请求成功对包含的结构数据进行处理
45. if(rootObj.contains("result"))
46. {
48. }
49. return 0;
50. }
51. else
52. {
53. //请求失败对对应的处理
54. return codeStr.toInt();
55. }
56. }
`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
4.上传参数和文件POST请求
`
1. int PostRequestWithFile(QString paramer1, QString paramer2,QString filePath)
2. {
4. //生成对应的网址请求
5. QFileInfo fileInfo(filePath);
6. QString fileName =fileInfo.fileName();
8. QFile* inputFile = new QFile(filePath);
9. inputFile->open(QIODevice::ReadOnly);
11. //multipart请求
12. QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
13. //文件块
14. QHttpPart filePart;
15. filePart.setHeader(QNetworkRequest::ContentDispositionHeader,
16. QVariant(QString("form-data; name=\"uploadfile\";filename=\"%1\"").arg(fileName)));
17. filePart.setBodyDevice(inputFile);
18. inputFile->setParent(multiPart);
19. multiPart->append(filePart);
21. QHttpPart paramer1Part;
22. paramer1Part.setHeader(QNetworkRequest::ContentDispositionHeader,QVariant("form-data; name=\"paramer1\""));
23. paramer1Part.setBody(paramer1.toUtf8());
24. multiPart->append(paramer1Part);
26. QHttpPart paramer2Part;
27. paramer2Part.setHeader(QNetworkRequest::ContentDispositionHeader,QVariant("form-data; name=\"paramer2\""));
28. paramer2Part.setBody(paramer2.toUtf8());
29. multiPart->append(paramer2Part);
32. //生成对应的网址请求
33. QNetworkRequest request;
34. QString scheme = "http";
35. QString serverAddr = "192.168.0.1";
36. QString port = "80";
37. QString requestHeader = scheme + QString("://") + serverAddr + QString(":") + port;
38. QString fullRequest = requestHeader + "/api/v1/user/postrequestwithfile";
39. request.setUrl(QUrl(fullRequest));
41. //发送请求
42. QNetworkAccessManager manager;
43. QNetworkReply *reply = manager.post(request,multiPart);
44. multiPart->setParent(reply);
46. QEventLoop eventLoop;
47. QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)),&eventLoop, SLOT(quit()));
48. eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
50. if(reply->error() != QNetworkReply::NoError)
51. {
52. return reply->error();
53. }
55. //解析返回的Json结果
56. QByteArray replyData = reply->readAll();
57. QJsonParseError json_error;
58. QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
59. if(json_error.error != QJsonParseError::NoError)
60. {
61. return -1;
62. }
63. QJsonObject rootObj = jsonDoc.object();
64. QString codeStr = rootObj.value("code").toString();
65. if (codeStr.compare("200") == 0)
66. {
67. //返回代码为200的时候证明请求成功对包含的结构数据进行处理
68. if(rootObj.contains("result"))
69. {
71. }
72. return 0;
73. }
74. else
75. {
76. //请求失败对对应的处理
77. return codeStr.toInt();
78. }
79. }
`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- 下载文件GET请求
1. int DownloadFileFromWeb(QString fileUrl,QString&fileSavePath)
2. {
3. QNetworkRequest request;
4. QUrl url(fileUrl);
5. QFileInfo fileInfo(url.path());
6. QString fileName = fileInfo.fileName();
7. QNetworkAccessManager *accessManager=new QNetworkAccessManager();
8. request.setUrl(url);
9. QNetworkReply *reply = accessManager->get(request);
10. QEventLoop loop;
11. QObject::connect(accessManager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
12. //如果需要下载进度需要关联对应的信号
13. //connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(LoadProgress(qint64, qint64)));
14. loop.exec(QEventLoop::ExcludeUserInputEvents);
16. //获取下载返回值
17. QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
18. if (statusCode.toInt() != 200)
19. {
20. return -1;
21. }
23. //保存下载的文件
24. QFile file(fileSavePath);
25. if(!file.open(QIODevice::WriteOnly))
26. {
27. return -2;
28. }
29. file.write(reply->readAll());
30. file.close();
31. return 0;
32. }
标签:Http,Qt,request,通信,return,QString,error,reply,请求
From: https://www.cnblogs.com/cps666/p/17341130.html