有没有办法将QHttpMultiPart
转换为QByteArray
或其他类似的二进制数据?
我发现QHttpMultiPart
编写邮件数据格式非常方便,但似乎非常依赖于QNetworkAccessManager
框架,并且就我搜索而言,没有直接的方法可以做到这一点。
我最接近的是将QHttpMultiPart
附加到QNetworkReply
对象,该对象派生自QIODevice
,然后使用QIODevice::readAll()
,但是QNetworkReply
没有公共建设者。
答案 0 :(得分:0)
您可以继承QNetworkAccessManager
:其createRequest()
方法(您必须实施)将收到QIODevice
,其中包含使用POST
请求发送的所有数据;所以你只需要在你的虚假网络访问管理器上拨打post(..., multiPart)
,你就可以读取数据了。
这是我写的辅助课:
multipart.h:
#include <QByteArray>
#include <QIODevice>
#include <QScopedPointer>
class QHttpMultiPart;
class MultipartPrivate;
class Multipart
{
public:
Multipart();
virtual ~Multipart();
QByteArray toByteArray(QHttpMultiPart *multiPart);
private:
QScopedPointer<MultipartPrivate> d_ptr;
Q_DECLARE_PRIVATE(Multipart)
};
multipart.cpp:
#include "multipart.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
class FakeReply: public QNetworkReply
{
Q_OBJECT
public:
FakeReply(const QNetworkRequest &req, QNetworkAccessManager *parent):
QNetworkReply(parent)
{
Q_UNUSED(req);
QNetworkReply::open(QIODevice::ReadOnly);
}
void abort() override {}
qint64 readData(char *, qint64) override { return 0; }
};
class MultipartPrivate: public QNetworkAccessManager
{
Q_OBJECT
using QNetworkAccessManager::QNetworkAccessManager;
QNetworkReply *createRequest(Operation op, const QNetworkRequest &req,
QIODevice *outgoingData) override {
Q_UNUSED(op);
m_data = outgoingData->readAll();
return new FakeReply(req, this);
}
public:
QByteArray m_data;
};
Multipart::Multipart():
d_ptr(new MultipartPrivate)
{
}
Multipart::~Multipart()
{
}
QByteArray Multipart::toByteArray(QHttpMultiPart *multiPart)
{
Q_D(Multipart);
QNetworkRequest dummy(QUrl("http://multipart.test"));
delete d->post(dummy, multiPart);
return d->m_data;
}
#include "multipart.moc"
您还可以在此处找到几个单元测试: https://gitlab.com/accounts-sso/libauthentication/commit/7d84cb417f756e663dca7362457b28bc53a1096a