QT之Http请求

今天我们介绍一下QT的http请求,这里有post和get两种方式

一、post请求方式:参数分为网址和具体请求值两个部分,有时候还需要设置头信息,看具体情况定

 1 void MainWindow::sendPostRequest()
 2 {
 3     QNetworkAccessManager *m_pHttpMgr = new QNetworkAccessManager();
 4     //设置url
 5     QString url = "http://10.0.0.20:8005/order/charge";
 6     //设置头信息
 7     QNetworkRequest requestInfo;
 8     requestInfo.setUrl(QUrl(url));
 9     requestInfo.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
10 //  requestInfo.setRawHeader("Content-Type","application/json");//服务器要求的数据头部
11 //  requestInfo.setRawHeader("Accept","text/json,*/*;q=0.5");//服务器要求的数据头部
12 
13     //发送数据
14     QByteArray qByteHttpData = sendJson();
15     QNetworkReply *reply =  m_pHttpMgr->post(requestInfo, qByteHttpData);
16     //添加事件循环机制,返回后再运行后面的
17     QEventLoop eventLoop;
18     connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
19     eventLoop.exec();       //block until finish
20 
21     //错误处理
22     if (reply->error() == QNetworkReply::NoError)
23     {
24         qDebug() << "request protobufHttp NoError";
25     }
26     else
27     {
28         qDebug()<<"request protobufHttp handle errors here";
29         QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
30         //statusCodeV是HTTP服务器的相应码,reply->error()是Qt定义的错误码,可以参考QT的文档
31         qDebug( "request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error());
32         qDebug(qPrintable(reply->errorString()));
33     }
34 
35     //请求收到的结果
36     QByteArray responseByte = reply->readAll();
37

二、get请求方式:参数和网址拼接到一起请求

 1 void MainWindow::sendGetRequest()
 2 {
 3     QNetworkAccessManager *m_pHttpMgr = new QNetworkAccessManager();
 4     //设置url
 5     QString url = "http://10.0.0.20:8005/vending_machine/items/ac83f39ea268";//fae4b325e52c
 6     QNetworkRequest requestInfo;
 7     requestInfo.setUrl(QUrl(url));
 8 
 9     //添加事件循环机制,返回后再运行后面的
10     QEventLoop eventLoop;
11     QNetworkReply *reply =  m_pHttpMgr->get(requestInfo);
12     connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
13     eventLoop.exec();       //block until finish
14     //错误处理
15     if (reply->error() == QNetworkReply::NoError)
16     {
17         qDebug() << "request protobufHttp NoError";
18     }
19     else
20     {
21         qDebug()<<"request protobufHttp handle errors here";
22         QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
23         //statusCodeV是HTTP服务器的相应码,reply->error()是Qt定义的错误码,可以参考QT的文档
24         qDebug( "request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error());
25         qDebug(qPrintable(reply->errorString()));
26     }
27     //请求返回的结果
28     QByteArray responseByte = reply->readAll();
29     qDebug() << responseByte;
30

 三、主要区别:

get用于请求获取数据,post向指定的资源创建修改数据

get把参数包含在URL中(长度有限制),POST通过请求实体传递参数(安全)

 

  

posted @ 2018-08-20 17:28  徐沛东  阅读(24794)  评论(6编辑  收藏  举报