×
Namespaces

Variants
Actions

在Qt中如何通过QNetworkAccessManager post http 请求

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Article
Created: ()
Last edited: renlin (11 Jul 2012)

Contents

介绍

本文将介绍如何通过QNetworkAccessManager post http 请求,接下来我们将看下具体实现

代码实现

.h

#include <QObject>
#include <QString>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QByteArray>
class QunarNetwork : public QObject
{
Q_OBJECT
 
public:
QunarNetwork(QObject *parent = 0);
signals:
void response(int len);
void error(int errCode);
public slots:
void post(QString strUrl);
void replyFinished(QNetworkReply* reply);
private:
QNetworkAccessManager* m_manager;
};

.cpp

#include "qunarNetwork.h"
#include <QDebug>
#include <QBuffer>
 
QunarNetwork::QunarNetwork(QObject *parent) :
QObject(parent)
{
m_manager = new QNetworkAccessManager(this);
connect(m_manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
}
 
void QunarNetwork::replyFinished(QNetworkReply *reply)
{
if(reply && reply->error() == QNetworkReply::NoError) {
QByteArray data = reply->readAll();
int len = data.size();
emit this->response(len);
} else {
emit this->error((int)reply->error());
}
reply->close();
}
 
void QunarNetwork::post(QString strUrl)
{
QNetworkRequest request;
request.setUrl(QUrl(strUrl));
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
 
m_manager->post(request, QByteArray("uid=0000000000&vid=10001001&cid=C1000&pid=10010&gid=9631B6DF-88E8-7ADA-C2F7-1CA3E07593FB&t=fmixwaylist&ke=691EE20AB30A4EB178776247719A4581F4DE58C5&param=5156A1DC57B15A7E786053B9A2ABEF1701032227AFAEAF756F65625AAF91B1FF1605F42033ACBABD5E767E6375B191BDAD9C9BACB99E9AB89EB0BAA7AF616B666DAA94A1ADA97276636966A9A69FAEBBAD61785D64B191B0BBAA666BBA939B68&cp=2&re=0"));
}

值得说明的是,在post方法中,我们需要构造一个http 报文,通过setHeader() 函数构建报文头,post的第二个参数 跟的是 post 报文体。

代码下载

File:NetWorkTest.zip

相关链接

Add categories below. Remove Category:Draft when the page is complete or near complete

This page was last modified on 11 July 2012, at 06:16.
288 page views in the last 30 days.
×