QNetworkAccessManager - 如何发送“PATCH”请求

时间:2015-12-03 12:10:26

标签: qt httprequest qnetworkaccessmanager qtnetwork qnetworkrequest

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

如何发送“PATCH”请求?

3 个答案:

答案 0 :(得分:6)

所以我们很清楚,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";

答案 1 :(得分:1)

尝试:

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

答案 2 :(得分:1)

由于QNetworkAccessManager不隐式支持PATCH,因此我创建了以下类QNetworkAccessManagerWithPatch。用它代替QNetworkAccessManager,您将拥有与patch()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
};