Home > Blockchain >  Getting an unsupported media type error while having a json object posted and content-type set to ap
Getting an unsupported media type error while having a json object posted and content-type set to ap

Time:05-05

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

}

CodePudding user response:

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