利用Qt提供的类实现向服务器发送post和get请求:
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonValue>
#include <QString>
#include <QDebug>
#include <QFile>
#include <QDateTime>
#include <QDir>
#include <QThread>
#pragma execution_character_set("utf-8")
void sendPostRequest()
{
QNetworkAccessManager *m_pHttpMgr = new QNetworkAccessManager();
QString url = "http://localhost:80/post";
QNetworkRequest requestInfo;
requestInfo.setUrl(QUrl(url));
requestInfo.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
QJsonObject regionObject;
regionObject.insert("name","333");
regionObject.insert("height", "2");
regionObject.insert("dir", "0");
QJsonArray pointAry;
pointAry.append(0.8);
pointAry.append(1.0);
pointAry.append(0.0);
pointAry.append(1.8);
pointAry.append(2.0);
pointAry.append(0.0);
regionObject.insert("points", QJsonValue(pointAry));
QJsonObject jsonObject;
jsonObject.insert("Code", "asss");
jsonObject.insert("parentId", 0);
jsonObject.insert("depot", "past");
jsonObject.insert("region", QJsonValue(regionObject));
QJsonDocument jsonDoc;
jsonDoc.setObject(jsonObject);
QByteArray qByteHttpData = jsonDoc.toJson();
QNetworkReply *reply = m_pHttpMgr->post(requestInfo, qByteHttpData);
QEventLoop eventLoop;
QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec();
if (reply->error() != QNetworkReply::NoError)
{
qDebug()<<"request protobufHttp handle errors here";
QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
qDebug( "request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error());
qDebug(qPrintable(reply->errorString()));
}
QByteArray responseByte = reply->readAll();
QString strRes = responseByte;
qDebug() << "Post:" << strRes;
}
void sendGetRequest()
{
QNetworkAccessManager *m_pHttpMgr = new QNetworkAccessManager();
QString url = "http:
QNetworkRequest requestInfo;
requestInfo.setUrl(QUrl(url));
QEventLoop eventLoop;
QNetworkReply *reply = m_pHttpMgr->get(requestInfo);
QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec();
if (reply->error() != QNetworkReply::NoError)
{
qDebug()<<"request protobufHttp handle errors here";
QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
qDebug( "request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error());
qDebug(qPrintable(reply->errorString()));
}
QByteArray responseByte = reply->readAll();
QString strRes = responseByte;
qDebug() << "Get:" << strRes;
QFile file(QDir::currentPath() + "/myResponde.json");
if(!file.open(QIODevice::ReadWrite))
{
qDebug() << "File open error";
}
file.write(responseByte);
file.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
sendPostRequest();
return a.exec();
}
|