在发布 json object 并将 content-type 设置为 application/json 时出现不受支持的媒体类型错误
Getting an unsupported media type error while having a json object posted and content-type set to application/json
我正在做一个小测试项目,目标是通过 Keycloak API 登录并获取我的访问令牌。
我面临的问题是我收到 415 错误“不受支持的媒体类型”,如下所示:
HTTP error
我已经尝试将内容类型 header 设为
- text/plain
- application/x-www-form-urlencoded
- application/json
这是我的代码:
void MainWindow::on_realmButton_clicked()
{
QNetworkRequest req{QUrl(QString("http://localhost:8080/realms/demo/protocol/openid-connect/token"))};
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QJsonObject body;
body["client_id"] = "demo-client";
body["grant_type"] = "password";
body["client_secret"] = "CLIENT_SECRET";
body["scope"] = "openid";
body["username"] = "user";
body["password"] = "password";
QJsonDocument document(body);
QByteArray bytes = document.toJson();
qDebug() << "JSON Object :" << bytes.toStdString().c_str();
netReply = netManager->post(req, bytes);
connect(netReply, &QNetworkReply::readyRead, this, &MainWindow::readData);
connect(netReply, &QNetworkReply::finished, this, &MainWindow::finishReading);
}
尝试类似的东西。编辑:为清楚起见添加此注释。 “protocol/openid-connect/token 端点需要形式编码的正文,而不是 JSON 正文。”
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QUrl body;
body.addQueryItem("client_id","demo-client");
.
.
.
networkManager->post(req, body.toString(QUrl::FullyEncoded).toUtf8());
我正在做一个小测试项目,目标是通过 Keycloak API 登录并获取我的访问令牌。 我面临的问题是我收到 415 错误“不受支持的媒体类型”,如下所示: HTTP error
我已经尝试将内容类型 header 设为
- text/plain
- application/x-www-form-urlencoded
- application/json
这是我的代码:
void MainWindow::on_realmButton_clicked()
{
QNetworkRequest req{QUrl(QString("http://localhost:8080/realms/demo/protocol/openid-connect/token"))};
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QJsonObject body;
body["client_id"] = "demo-client";
body["grant_type"] = "password";
body["client_secret"] = "CLIENT_SECRET";
body["scope"] = "openid";
body["username"] = "user";
body["password"] = "password";
QJsonDocument document(body);
QByteArray bytes = document.toJson();
qDebug() << "JSON Object :" << bytes.toStdString().c_str();
netReply = netManager->post(req, bytes);
connect(netReply, &QNetworkReply::readyRead, this, &MainWindow::readData);
connect(netReply, &QNetworkReply::finished, this, &MainWindow::finishReading);
}
尝试类似的东西。编辑:为清楚起见添加此注释。 “protocol/openid-connect/token 端点需要形式编码的正文,而不是 JSON 正文。”
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QUrl body;
body.addQueryItem("client_id","demo-client");
.
.
.
networkManager->post(req, body.toString(QUrl::FullyEncoded).toUtf8());