qt 之 Creating an HTTP network request in Qt Overview

本文介绍如何使用Qt进行HTTP网络请求,包括GET和POST方法。演示了如何设置请求头、发送表单数据及文件上传等操作。

post data in Qt5

QUrl url;
QByteArray postData;

url.setUrl("http://myurl....");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");

Qstring postKey = 'city';
QString postValue = 'Brisbane';

postData.append(postKey).append("=").append(postValue).append("&");         
networkManager.post(request,postData);
 QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

 QHttpPart textPart;
 textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"text\""));
 textPart.setBody("my text");

 QHttpPart imagePart;
 imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
 imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\""));
 QFile *file = new QFile("image.jpg");
 file->open(QIODevice::ReadOnly);
 imagePart.setBodyDevice(file);
 file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart

 multiPart->append(textPart);
 multiPart->append(imagePart);

 QUrl url("http://my.server.tld");
 QNetworkRequest request(url);

 QNetworkAccessManager manager;
 QNetworkReply *reply = manager.post(request, multiPart);
 multiPart->setParent(reply); // delete the multiPart with the reply
 // here connect signals etc.


 

Creating an HTTP network request in Qt

Overview

This code snippet demonstrates how to use QNetworkAccessManager for sending an HTTP request.

Note: In order to use this code, you need to have Qt installed on your platform.


Header

#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
 
QNetworkAccessManager* nam;


Source

Create QNetworkAccessManager and start listening for its finished signal.

nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply*)),
this, SLOT(finishedSlot(QNetworkReply*)));

HTTP GET request:

QUrl url("http://www.forum.nokia.wiki");
QNetworkReply* reply = nam->get(QNetworkRequest(url));
// NOTE: Store QNetworkReply pointer (maybe into caller).
// When this HTTP request is finished you will receive this same
// QNetworkReply as response parameter.
// By the QNetworkReply pointer you can identify request and response.

When the QNetworkAccessManager::finished signal is received, the HTTP request is completed.

void MyHttpEngine::finishedSlot(QNetworkReply* reply)
{
// Reading attributes of the reply
// e.g. the HTTP status code
QVariant statusCodeV =
reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
// Or the target URL if it was a redirect:
QVariant redirectionTargetUrl =
reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
// see CS001432 on how to handle this
 
// no error received?
if (reply->error() == QNetworkReply::NoError)
{
// read data from QNetworkReply here
 
// Example 1: Creating QImage from the reply
QImageReader imageReader(reply);
QImage pic = imageReader.read();
 
// Example 2: Reading bytes form the reply
QByteArray bytes = reply->readAll(); // bytes
QString string(bytes); // string
}
// Some http error received
else
{
// handle errors here
}
 
// We receive ownership of the reply object
// and therefore need to handle deletion.
reply->deleteLater();
    reply0
;
}
Creating an HTTP network request is one of the baseline tasks required of most developers in this day and age. This article spells out in clear, yet concise steps, the information required to accomplish this task.

In addition to a relevant list of preconditions, this article steps the reader through the relevant coding sections in a well thought out manner. The frequent line level coding documentation was useful for this reader (and better than his own). In the example code, the author demonstrates two alternate ways of using the reply read from the network, both of which will be helpful to developers that are new to QT.

--beakesland 21:26, 24 September 2009 (UTC)


This code goes against QT's own documentation

From the Article:


   // We receive ownership of the reply object
   // and therefore need to handle deletion.
   delete reply;


QT documentation (for signal finished()):

   Note: Do not delete the reply object in the slot connected to this signal. Use deleteLater().

Suggest changing the code to reply.deleteLater();

pasihir 12:05, 16 November 2010 (UTC)


This code:

   QByteArray bytes = reply.readAll();  // bytes 
   QString string(bytes); // string

is wrong. Use

   QString string = QString::fromXXX(bytes); 

where XXX is the encoding of the data in the bytearray, ie fromUtf8(...)

It would be really helpful to have Qt Code double-checked by someone from Qt Dev, or at the very least allow editing of this kind of articles. Wrong information is worse than no information.


-apoenitz2 21:24, 19 May 2011


Patxitron - The C++ is wrong

In adition to the errors pointed by -apoenitz2, in the MyHttpEngine::finishedSlot since reply is a pointer to QNetworkReply the line

QByteArray bytes = reply.readAll();  // bytes 

is wrong. It should be

QByteArray bytes = reply->readAll();  // bytes 

Best regards


Patxitron

Patxitron (talk) 16:43, 26 September 2013 (EEST)

Hamishwillee - Thanks Patxitron

I've fixed up your error, as it is basic C++. Didn't fix the other stuff. This is a wiki, so if you're absolutely sure of yourself then you can change the article to fix it yourself.

Regards

Hamish

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值