4

我正在尝试向我的 firebase 应用程序发送“PATCH”请求。据我所知,QNetworkManager 不支持“Patch”请求。

如何发送“PATCH”请求?

4

3 回答 3

7

所以我们很清楚 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";
于 2015-12-03T12:10:25.617 回答
1

由于QNetworkAccessManager不支持 PATCH 隐式,我创建了以下类QNetworkAccessManagerWithPatch。使用它代替,QNetworkAccessManager您将拥有与patch()for 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
};
于 2020-02-07T10:59:15.557 回答
1

尝试:

QNetworkAccessManager* manager = new QNetworkAccessManager();
QNetworkRequest request("http://<domain>/<path>/");
QHttpMultiPart* multipart = new QHttpMultiPart();
//... Add your data in multipart
manager->sendCustomRequest(request, "PATCH", multipart);
于 2017-06-26T23:37:58.527 回答