QNetworkAccessManager - 如何发送 "PATCH" 请求

QNetworkAccessManager - How to send "PATCH" request

我正在尝试向我的 firebase application.As 发送一个 "PATCH" 请求,据我所知 QNetworkManager 不支持 "Patch" 请求。

如何发送 "PATCH" 请求?

所以我们很清楚QNetworkAccessManager中没有名为"patch"的方法 因此我使用了 "sendCustomRequest" 但使用了 QBuffer。因为 QNetworkManager 需要一个 QIODevice 对象。

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

尝试:

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

由于 QNetworkAccessManager 不隐式支持 PATCH,我创建了以下支持的 class QNetworkAccessManagerWithPatch。使用它代替 QNetworkAccessManagerpatch() 将具有与 post()put() 等相同的 3 个变体

在此处获取 Github 要点:https://gist.github.com/paulmasri/efafb8ee350a8ce84a6657a30eb4eb8a

或者直接从这里获取代码:(另存为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
};