简体   繁体   中英

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. The problem i'm facing is that i got a 415 error "unsupported media type" as the following: HTTP error

I've tried content type header as

  • text/plain
  • application/x-www-form-urlencoded
  • application/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."

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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