Sending a Post request with JSON and Image data
Unsolved
General and Desktop
-
Facing the issue in sending the post request with JSON and image data
Here is the codemanager = new QNetworkAccessManager(this); QNetworkRequest request; QUrl url(location); request.setUrl(url); request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json")); request.setRawHeader("Authorization", "Basic " + (QString("%1:%2").arg("admin").arg("admin").toLatin1()).toBase64()); /* multi part */ multiPart = new QHttpMultiPart(manager); jsonPart = new QHttpPart(); jsonPart->setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain")); jsonPart->setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"data\"")); QByteArray data = jsonData.toUtf8(); // conversion of json to byte array qDebug() << "QByte Array data: "<< data; jsonPart->setBody(data); multiPart->append(*jsonPart); imagePart = new QHttpPart(); imagePart->setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png")); imagePart->setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"newImage.jpg\"")); file = new QFile(jpegFileLocation); file->open(QIODevice::ReadOnly); qDebug() << "File Open Status: " << file->isOpen(); imagePart->setBodyDevice(file); multiPart->append(*imagePart); QNetworkReply* reply = manager->post(request, multiPart); QObject::connect(reply, &QNetworkReply::finished, [=](){ if(reply->error() == QNetworkReply::NoError){ QString contents = QString::fromUtf8(reply->readAll()); qDebug() << "Received Data: " << contents; } else{ QString err = reply->errorString(); qDebug() << "Error:" <<reply->error(); qDebug() << "Error String:" << err; } reply->deleteLater(); });
getting Error in the reply
Error: QNetworkReply::ProtocolInvalidOperationError
-
@PrakharP On a quick inspection, the main request is not of type "application/json" but probably "multipart/form-data" or "multipart/mixed" , the JSON part is not "text/plain", and the PNG image has an incongruous JPG name but might be OK. Not overly surprising that the server is confused.
Study the example here more closely.