Qt:使用QNetworkAccessManager将json中的base64文件发送到SendGrid并发布

时间:2019-03-03 05:44:34

标签: c++ qt

我在使用SendGrid API的简单任务上遇到了麻烦。

下面有一个简洁的程序,但是无法正常工作。我的输出为空。我尝试安装OpenSSL(https://slproweb.com/products/Win32OpenSSL.html),但没有帮助。

代码如下:

#include <QCoreApplication>

#include <QFile>
#include <QByteArray>
#include <QUrl>
#include <QUrlQuery>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QJsonObject>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QString>
#include <QSslConfiguration>
#include <QSsl>

int main(int argc, char *argv[])
{
    QString fileToAttach = "C:\\Path\\To\\picture.jpg";
    QString email = "email@example.com";

    QFile* file = new QFile(fileToAttach);
    file->open(QIODevice::ReadOnly);
    QByteArray image = file->readAll();
    QString encoded = QString(image.toBase64());

    QByteArray jsonData(QString("{ \"personalizations\": [ { \"to\": [ { \"email\": \"" + email + "\" } ], \"subject\": \"Hello, World!\" } ], \"from\": { \"email\": \"info@example.com\" }, \"content\": [ { \"type\": \"text/html\", \"value\": \"Hello there\" } ], \"attachments\": [ { \"content\": \"" + encoded + "\", \"filename\": \"test.jpg\", \"content_id\": \"test.jpg\", \"type\": \"image/jpeg\" } ] }").toUtf8());

    //qDebug() << jsonData;

    QNetworkAccessManager *networkManager = new QNetworkAccessManager();

    QNetworkRequest request(QUrl("https://api.sendgrid.com/v3/mail/send"));

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", "Bearer <KEY_HERE>");
    request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(jsonData.size()));

    QSslConfiguration config = QSslConfiguration::defaultConfiguration();
    config.setProtocol(QSsl::TlsV1_2);
    request.setSslConfiguration(config);

    QNetworkReply *output = networkManager->post(request, jsonData);

    qDebug() << "Output: " << output->readAll();

    delete file;

}

和.pro

QT -= gui
QT += network

CONFIG += c++11 console
CONFIG -= app_bundle

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
        main.cpp

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

在此先感谢您的帮助。我将尝试快速回复评论。这似乎是一个简单的任务,但是我很难过。

0 个答案:

没有答案