PostHttp.cpp Example File
httptest/src/PostHttp.cpp
#include "PostHttp.hpp"
#include "AppSettings.hpp"
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslConfiguration>
#include <QUrl>
PostHttp::PostHttp(QObject* parent)
: QObject(parent)
, m_networkAccessManager(new QNetworkAccessManager(this))
{
}
void PostHttp::post(const QString &body)
{
const QUrl url("http://httpbin.org/post");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "text/plain");
if (AppSettings::isUsingHttps()) {
request.setUrl(QUrl("https://httpbin.org/post"));
QSslConfiguration config = request.sslConfiguration();
config.setPeerVerifyMode(QSslSocket::VerifyNone);
config.setProtocol(QSsl::TlsV1);
request.setSslConfiguration(config);
}
QNetworkReply* reply = m_networkAccessManager->post(request, body.toAscii());
bool ok = connect(reply, SIGNAL(finished()), this, SLOT(onGetReply()));
Q_ASSERT(ok);
Q_UNUSED(ok);
}
void PostHttp::onGetReply()
{
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
QString response;
if (reply) {
if (reply->error() == QNetworkReply::NoError) {
const int available = reply->bytesAvailable();
if (available > 0) {
const QByteArray buffer(reply->readAll());
response = QString::fromUtf8(buffer);
}
} else {
response = tr("Error: %1 status: %2").arg(reply->errorString(), reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString());
qDebug() << response;
}
reply->deleteLater();
}
if (response.trimmed().isEmpty()) {
response = tr("Unable to retrieve post response");
}
emit complete(response);
}