简体   繁体   English

在发布 json object 并将内容类型设置为 application/json 时出现不受支持的媒体类型错误

[英]Getting an unsupported media type error while having a json object posted and content-type set to application/json

I'm doing a small test projet, the goal is to log throught Keycloak API and get my access token.我正在做一个小型测试项目,目标是通过 Keycloak API 登录并获取我的访问令牌。 The problem i'm facing is that i got a 415 error "unsupported media type" as the following: HTTP error我面临的问题是我收到 415 错误“不受支持的媒体类型”,如下所示: HTTP 错误

I've tried content type header as我试过内容类型 header 作为

  • text/plain文本/纯文本
  • application/x-www-form-urlencoded应用程序/x-www-form-urlencoded
  • application/json应用程序/json

Here is my code:这是我的代码:

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);

}

Try something like.尝试类似的东西。 Edit: add this note for clarity.编辑:为清楚起见添加此注释。 "The protocol/openid-connect/token endpoint expects form encoded body, not a JSON body." “协议/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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM