POST-通过与 Qt5 的 HTTPS 连接请求 JSON 数据

POST-Request with JSON Data over HTTPS Connection with Qt5

我正在尝试通过 Qt5 通过 HTTPS 连接向 Web-API 发送 POST 请求,但我不断收到以下错误消息:

Failure "Error downloading https://.../login - server replied: BAD REQUEST"

Reply:"{"error_tag": "ARGUMENT_MISSING", "error_code": 19, "error_extra": {"argument": "email"}, "error": "Required argument is missing"}"

似乎 HTTPS 连接有效,但 POST 请求有问题...

    void connection::sendLoginData(){
        QUrl url = QString("https://.../login");
        QNetworkRequest req(url);
//Creating the JSON-Data
        QJsonDocument json;
        QJsonObject data;

        data["email"] = QString("a@g.com");
        data["password"] = QString("---");

        json.setObject(data);
        QByteArray jsonPost = QJsonDocument(data).toJson();

        req.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json; charset=utf-8"));
        req.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(jsonPost.size()));

//Sending the Request
        QNetworkReply *reply = manager->post(req,jsonPost);

    // Connection via HTTPS
        QFile certFile(SSLCERTIFICATE);
        certFile.open(QIODevice::ReadOnly);
        QSslCertificate cert(&certFile, QSsl::Pem);
        QSslSocket * sslSocket = new QSslSocket(this);
        sslSocket->addCaCertificate(cert);
        QSslConfiguration configuration = sslSocket->sslConfiguration();
        configuration.setProtocol(QSsl::TlsV1_2);

        sslSocket->setSslConfiguration(configuration);
        reply->setSslConfiguration(configuration);

    }

这是当 QNetworkReply 得到回复时调用的插槽:

void connection::onFinished(QNetworkReply *reply){
    if (reply->error() == QNetworkReply::NoError) {
        //success
        qDebug() << "Success" <<reply->readAll();
        delete reply;
    }
    else {
        //failure
        qDebug() << "Failure" <<reply->errorString();
        qDebug() << "Reply: " << reply->readAll();
        delete reply;
    }
}

QNetworkReply 的 Signal "finished" 当然是连接到 "onFinished"-Slot

    MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    manager = new QNetworkAccessManager;
    ui->setupUi(this);
    Connector = new connection(ui,manager);
connect(manager,SIGNAL(finished(QNetworkReply*)),Connector,SLOT(onFinished(QNetworkReply*)));

}

也许有人可以告诉我 POST-Request 有什么问题?查看服务器的回复,似乎 JSON-数据从未发送过,或者格式错误...

由于您没有提供确切的 URL,我建议您尝试检查 url.isValid() 和 url.errorString().

我刚遇到一个问题,代码在 Qt 4.8 中运行良好,但在 Qt 5.4 中,我所有的 POST 请求都得到了 400 Bad Request 回复。 我通过 Wireshark 查看了 TCP 转储,发现 URL 是错误的。 在我的例子中 url.setPath("api/register"); 是导致问题的行。应该是 url.setPath("/api/register");

希望对您有所帮助。