我正在尝试通过Qt5通过HTTPS连接向Web-API发送POST请求,但我不断收到以下错误消息:
失败"下载 https://.../login 时出错 - 服务器回复:错误请求"
回复:
"{"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);
}
这是在QNetworkReprat得到回复时调用的Slot:
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 的信号"完成"当然连接到"onFinish"插槽
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 请求有什么问题?查看服务器的回复,似乎 JSON 数据从未发送过,或者以某种方式以错误的方式格式化......
由于您没有提供确切的URL,因此我建议您尝试检查url.isValid()
和URL。errorString()
.
我刚刚遇到了一个问题,代码在Qt 4.8中运行良好,但是在Qt 5.4中,我所有的POST请求都得到了400个错误请求回复。我通过Wireshark查看了TCP转储,发现URL是错误的。就我而言url.setPath("api/register");
是导致问题的线路。它应该被url.setPath("/api/register");
希望对您有所帮助。