简体   繁体   中英

QNetworkAccessManager - How to send "PATCH" request

I am trying to send a "PATCH" request to my firebase application.As far as I read QNetworkManager doesn't support "Patch" request.

How can I send "PATCH" request ?

So we are clear that there is no method in QNetworkAccessManager named "patch" Therefore I have used "sendCustomRequest" but with QBuffer. Because QNetworkManager requires a QIODevice object.

QString destination="";
currentNode.replace(QString("/").append(latestNode),"");
destination
        .append(host)
        .append(currentNode)
        .append(".json");
QString jsonString=QString(QString("{").append("\"").append(latestNode).append("\"").append(":").append("\"").append(str).append("\"").append(QString("}")));
QNetworkRequest request(destination);
request.setHeader(QNetworkRequest::ContentTypeHeader,
    "application/x-www-form-urlencoded");
qDebug()<<jsonString;
QBuffer *buffer=new QBuffer();
buffer->open((QBuffer::ReadWrite));
buffer->write(jsonString.toUtf8());
buffer->seek(0);
manager->sendCustomRequest(request,"PATCH",buffer);
qDebug()<<"posted";

try:

QNetworkAccessManager* manager = new QNetworkAccessManager();
QNetworkRequest request("http://<domain>/<path>/");
QHttpMultiPart* multipart = new QHttpMultiPart();
//... Add your data in multipart
manager->sendCustomRequest(request, "PATCH", multipart);

As QNetworkAccessManager does not support PATCH implicitly, I've created the following class QNetworkAccessManagerWithPatch that does. Use it in place of QNetworkAccessManager and you'll have the same 3 variants for patch() as there are for post() , put() , etc.

Get the Github gist here: https://gist.github.com/paulmasri/efafb8ee350a8ce84a6657a30eb4eb8a

Or take the code directly from here: (save as QNetworkAccessManagerWithPatch.h )

#pragma once

#include <QNetworkAccessManager>

class QNetworkAccessManagerWithPatch : public QNetworkAccessManager
{
    Q_OBJECT

public:
    explicit QNetworkAccessManagerWithPatch(QObject *parent = Q_NULLPTR)
        : QNetworkAccessManager(parent) {}

    QNetworkReply* patch(const QNetworkRequest &request, QIODevice *data)
    { return sendCustomRequest(request, "PATCH", data); }
    QNetworkReply* patch(const QNetworkRequest &request, const QByteArray &data)
    { return sendCustomRequest(request, "PATCH", data); }

#if QT_CONFIG(http)
    QNetworkReply *patch(const QNetworkRequest &request, QHttpMultiPart *multiPart)
    { return sendCustomRequest(request, "PATCH", multiPart); }
#endif
};

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