Revision control

+ {{>licenseInfo}}
+ #include "{{prefix}}HttpRequest.h"
+
+ #include <QtCore/qdatetime.h>
+ #include <QtCore/qdir.h>
+ #include <QtCore/qfileinfo.h>
+ #include <QtCore/QRandomGenerator>
+ #include <QtCore/qurl.h>
+ #include <QtCore/quuid.h>
+ #include <QtCore/QtGlobal>
+ #include <QtNetwork/qnetworkaccessmanager.h>
+ #include <QtNetwork/qnetworkrequestfactory.h>
+ #include <QtNetwork/qrestaccessmanager.h>
+
+ {{#contentCompression}}#include <zlib.h>{{/contentCompression}}
+ {{#cppNamespaceDeclarations}}
+ namespace {{this}} {
+ {{/cppNamespaceDeclarations}}
+
+ {{prefix}}HttpRequestInput::{{prefix}}HttpRequestInput()
+ {
+ initialize();
+ }
+
+ {{prefix}}HttpRequestInput::{{prefix}}HttpRequestInput(const QString &vUrlStr, const QString &vHttpMethod)
+ {
+ initialize();
+ m_urlStr = vUrlStr;
+ m_httpMethod = vHttpMethod;
+ }
+
+ void {{prefix}}HttpRequestInput::initialize()
+ {
+ m_varLayout = NOT_SET;
+ m_urlStr = "";
+ m_httpMethod = "GET";
+ }
+
+ {{prefix}}HttpRequestInput::{{prefix}}HttpRequestInput({{prefix}}HttpRequestInput &other)
+ {
+ m_urlStr = other.m_urlStr;
+ m_httpMethod = other.m_httpMethod;
+ m_varLayout = other.m_varLayout;
+ m_vars = other.m_vars;
+ m_headers = other.m_headers;
+ m_files = other.m_files;
+ m_requestBody = other.m_requestBody;
+ }
+
+ void {{prefix}}HttpRequestInput::addVar(const QString &key, const QString &value)
+ {
+ m_vars[key] = value;
+ }
+
+ void {{prefix}}HttpRequestInput::addFile(const QString &variableName, const QString &localFilename, const QString &requestFilename, const QString &mimeType)
+ {
+ {{prefix}}HttpFileElement file;
+ file.m_variableName = variableName;
+ file.m_localFilename = localFilename;
+ file.m_requestFilename = requestFilename;
+ file.m_mimeType = mimeType;
+ m_files.append(file);
+ }
+
+ void {{prefix}}HttpRequestInput::setHeaders(const QHttpHeaders &newHeaders)
+ {
+ m_headers = newHeaders;
+ }
+
+ namespace {{prefix}}HttpRequestWorker {
+
+ {{prefix}}HttpFileElement getHttpFileElement(const QMap<QString, {{prefix}}HttpFileElement> &files, const QString &fieldname)
+ {
+ if (!files.isEmpty()) {
+ if (fieldname.isEmpty()) {
+ return files.first();
+ } else if (files.contains(fieldname)) {
+ return files[fieldname];
+ }
+ }
+ return {{prefix}}HttpFileElement();
+ }
+
+ QByteArray *getMultiPartField(const QMap<QString, QByteArray *> &multiPartFields, const QString &fieldname)
+ {
+ if (!multiPartFields.isEmpty()) {
+ if (fieldname.isEmpty()) {
+ return multiPartFields.first();
+ } else if (multiPartFields.contains(fieldname)) {
+ return multiPartFields[fieldname];
+ }
+ }
+ return nullptr;
+ }
+
+ QString httpAttributeEncode(const QString &attributeName, const QString &input)
+ {
+ // result structure follows RFC 5987
+ bool needUtfEncoding = false;
+ QString result = "";
+ const QByteArray inputC = input.toLocal8Bit();
+ char c;
+ for (int i = 0; i < inputC.length(); i++) {
+ c = inputC.at(i);
+ if (c == '\\' || c == '/' || c == '\0' || c < ' ' || c > '~') {
+ // ignore and request utf-8 version
+ needUtfEncoding = true;
+ } else if (c == '"') {
+ result += "\\\"";
+ } else {
+ result += c;
+ }
+ }
+
+ if (result.length() == 0) {
+ needUtfEncoding = true;
+ }
+
+ if (!needUtfEncoding) {
+ // return simple version
+ return QString("%1=\"%2\"").arg(attributeName, result);
+ }
+
+ QString resultUtf8 = "";
+ for (int i = 0; i < inputC.length(); i++) {
+ c = inputC.at(i);
+ if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
+ resultUtf8 += c;
+ } else {
+ resultUtf8 += "%" + QString::number(static_cast<unsigned char>(inputC.at(i)), 16).toUpper();
+ }
+ }
+
+ // return enhanced version with UTF-8 support
+ return QString("%1=\"%2\"; %1*=utf-8''%3").arg(attributeName, result, resultUtf8);
+ }
+
+ QNetworkRequest getNetworkRequest({{prefix}}HttpRequestInput &input, QByteArray &requestContent, std::shared_ptr<QNetworkRequestFactory> factory, bool responseCompressionEnabled, bool requestCompressionEnabled)
+ {
+ QRandomGenerator randomGenerator = QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
+ // reset variables
+ requestContent = "";
+ bool isFormData = false;
+
+ // decide on the variable layout
+ if (input.m_files.length() > 0) {
+ input.m_varLayout = MULTIPART;
+ }
+ if (input.m_varLayout == NOT_SET) {
+ input.m_varLayout = input.m_httpMethod == "GET" || input.m_httpMethod == "HEAD" ? ADDRESS : URL_ENCODED;
+ }
+
+ // prepare request content
+ QString boundary = "";
+ if (input.m_varLayout == ADDRESS || input.m_varLayout == URL_ENCODED) {
+ // variable layout is ADDRESS or URL_ENCODED
+
+ if (input.m_vars.count() > 0) {
+ bool first = true;
+ isFormData = true;
+ for (QString key : input.m_vars.keys()) {
+ if (!first) {
+ requestContent.append("&");
+ }
+ first = false;
+
+ requestContent.append(QUrl::toPercentEncoding(key));
+ requestContent.append("=");
+ requestContent.append(QUrl::toPercentEncoding(input.m_vars.value(key)));
+ }
+
+ if (input.m_varLayout == ADDRESS) {
+ input.m_urlStr += "?" + requestContent;
+ requestContent = "";
+ }
+ }
+ } else {
+ // variable layout is MULTIPART
+ boundary = QString("__-----------------------%1%2")
+ .arg(QDateTime::currentDateTime().toSecsSinceEpoch())
+ .arg(randomGenerator.generate());
+ QString boundaryDelimiter = "--";
+ const QString newLine = "\r\n";
+
+ // add variables
+ for (const QString &key : input.m_vars.keys()) {
+ // add boundary
+ requestContent.append(boundaryDelimiter.toUtf8());
+ requestContent.append(boundary.toUtf8());
+ requestContent.append(newLine.toUtf8());
+
+ // add header
+ requestContent.append("Content-Disposition: form-data; ");
+ requestContent.append(httpAttributeEncode("name", key).toUtf8());
+ requestContent.append(newLine.toUtf8());
+ requestContent.append("Content-Type: text/plain");
+ requestContent.append(newLine.toUtf8());
+
+ // add header to body splitter
+ requestContent.append(newLine.toUtf8());
+
+ // add variable content
+ requestContent.append(input.m_vars.value(key).toUtf8());
+ requestContent.append(newLine.toUtf8());
+ }
+
+ // add files
+ for (QList<{{prefix}}HttpFileElement>::iterator fileInfo = input.m_files.begin(); fileInfo != input.m_files.end(); fileInfo++) {
+ QFileInfo fi(fileInfo->m_localFilename);
+
+ // ensure necessary variables are available
+ if (fileInfo->m_localFilename == nullptr
+ || fileInfo->m_localFilename.isEmpty()
+ || fileInfo->m_variableName == nullptr
+ || fileInfo->m_variableName.isEmpty()
+ || !fi.exists()
+ || !fi.isFile()
+ || !fi.isReadable()) {
+ // silent abort for the current file
+ continue;
+ }
+
+ QFile file(fileInfo->m_localFilename);
+ if (!file.open(QIODevice::ReadOnly)) {
+ // silent abort for the current file
+ continue;
+ }
+
+ // ensure filename for the request
+ if (fileInfo->m_requestFilename == nullptr || fileInfo->m_requestFilename.isEmpty()) {
+ fileInfo->m_requestFilename = fi.fileName();
+ if (fileInfo->m_requestFilename.isEmpty()) {
+ fileInfo->m_requestFilename = "file";
+ }
+ }
+
+ // add boundary
+ requestContent.append(boundaryDelimiter.toUtf8());
+ requestContent.append(boundary.toUtf8());
+ requestContent.append(newLine.toUtf8());
+
+ // add header
+ requestContent.append(
+ QString("Content-Disposition: form-data; %1; %2").arg(httpAttributeEncode("name", fileInfo->m_variableName), httpAttributeEncode("filename", fileInfo->m_requestFilename)).toUtf8());
+ requestContent.append(newLine.toUtf8());
+
+ if (fileInfo->m_mimeType != nullptr && !fileInfo->m_mimeType.isEmpty()) {
+ requestContent.append("Content-Type: ");
+ requestContent.append(fileInfo->m_mimeType.toUtf8());
+ requestContent.append(newLine.toUtf8());
+ }
+
+ requestContent.append("Content-Transfer-Encoding: binary");
+ requestContent.append(newLine.toUtf8());
+
+ // add header to body splitter
+ requestContent.append(newLine.toUtf8());
+
+ // add file content
+ requestContent.append(file.readAll());
+ requestContent.append(newLine.toUtf8());
+
+ file.close();
+ }
+
+ // add end of body
+ requestContent.append(boundaryDelimiter.toUtf8());
+ requestContent.append(boundary.toUtf8());
+ requestContent.append(boundaryDelimiter.toUtf8());
+ }
+
+ if (input.m_requestBody.size() > 0) {
+ requestContent.clear();
+ if (!isFormData && (input.m_varLayout != MULTIPART) && requestCompressionEnabled) {
+ requestContent.append(compress(input.m_requestBody, 7, {{prefix}}CompressionType::Gzip));
+ } else {
+ requestContent.append(input.m_requestBody);
+ }
+ }
+ QNetworkRequest request = factory->createRequest(input.m_urlStr);
+ if (request.header(QNetworkRequest::UserAgentHeader).isNull())
+ request.setHeader(QNetworkRequest::UserAgentHeader, "{{httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{apiVersion}}/cpp-qt{{/httpUserAgent}}");
+
+ if (requestContent.size() > 0 && !isFormData && (input.m_varLayout != MULTIPART)) {
+ if (!input.m_headers.contains(QHttpHeaders::WellKnownHeader::ContentType)) {
+ request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
+ } else {
+ request.setHeader(QNetworkRequest::ContentTypeHeader,
+ input.m_headers.combinedValue(QHttpHeaders::WellKnownHeader::ContentType));
+ }
+ if (requestCompressionEnabled) {
+ request.setRawHeader("Content-Encoding", "gzip");
+ }
+ } else if (input.m_varLayout == URL_ENCODED) {
+ request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
+ } else if (input.m_varLayout == MULTIPART) {
+ request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + boundary);
+ }
+
+ if (responseCompressionEnabled) {
+ request.setRawHeader("Accept-Encoding", "gzip");
+ } else {
+ request.setRawHeader("Accept-Encoding", "identity");
+ }
+ return request;
+ }
+
+ QByteArray parseResponse(const QRestReply &reply, const QString &workDir, QMap<QString, {{prefix}}HttpFileElement> *files)
+ {
+ QByteArray result;
+ QString contentDispositionHdr;
+ QString contentTypeHdr;
+ QString contentEncodingHdr;
+
+ if (!reply.networkReply())
+ return result;
+
+ QHttpHeaders headers;
+ if (reply.networkReply()->rawHeaderPairs().count() > 0)
+ headers = reply.networkReply()->headers();
+
+ for (qsizetype i = 0; i < headers.size(); ++i) {
+ const auto name = headers.nameAt(i);
+ const auto value = headers.valueAt(i);
+ if (name.compare(QString("Content-Disposition"), Qt::CaseInsensitive) == 0) {
+ contentDispositionHdr = QString::fromLatin1(value);
+ }
+ if (name.compare(QString("Content-Type"), Qt::CaseInsensitive) == 0) {
+ contentTypeHdr = QString::fromLatin1(value);
+ }
+ if (name.compare(QString("Content-Encoding"), Qt::CaseInsensitive) == 0) {
+ contentEncodingHdr = QString::fromLatin1(value);
+ }
+ }
+
+ if (!contentDispositionHdr.isEmpty()) {
+ auto contentDisposition = contentDispositionHdr.split(QString(";"), Qt::SkipEmptyParts);
+ auto contentType =
+ !contentTypeHdr.isEmpty() ? contentTypeHdr.split(QString(";"), Qt::SkipEmptyParts).first() : QStringLiteral("");
+ if ((contentDisposition.count() > 0) && (contentDisposition.first() == QString("attachment"))) {
+ QString filename = QUuid::createUuid().toString();
+ for (const auto &file : contentDisposition) {
+ if (file.contains(QString("filename"))) {
+ filename = file.split(QString("="), Qt::SkipEmptyParts).at(1);
+ break;
+ }
+ }
+ {{prefix}}HttpFileElement felement;
+ felement.saveToFile(QStringLiteral(""), workDir + QDir::separator() + filename, filename, contentType, reply.networkReply()->readAll());
+ if (files)
+ files->insert(filename, felement);
+ }
+
+ } else if (!contentTypeHdr.isEmpty()) {
+ auto contentType = contentTypeHdr.split(QString(";"), Qt::SkipEmptyParts);
+ if ((contentType.count() > 0) && (contentType.first() == QString("multipart/form-data"))) {
+ // TODO : Handle Multipart responses
+ } else {
+ if (!contentEncodingHdr.isEmpty()) {
+ auto encoding = contentEncodingHdr.split(QString(";"), Qt::SkipEmptyParts);
+ if (encoding.count() > 0) {
+ auto compressionTypes = encoding.first().split(',', Qt::SkipEmptyParts);
+ if (compressionTypes.contains("gzip", Qt::CaseInsensitive) || compressionTypes.contains("deflate", Qt::CaseInsensitive)) {
+ result = decompress(reply.networkReply()->readAll());
+ } else if (compressionTypes.contains("identity", Qt::CaseInsensitive)) {
+ result = reply.networkReply()->readAll();
+ }
+ }
+ } else {
+ result = reply.networkReply()->readAll();
+ }
+ }
+ }
+ reply.networkReply()->deleteLater();
+ return result;
+ }
+
+ QByteArray decompress(const QByteArray& data)
+ {
+ {{#contentCompression}}QByteArray result;
+ bool sts = false;
+ do {
+ z_stream strm{};
+ static const int CHUNK_SIZE = 8*1024;
+ char out[CHUNK_SIZE];
+ if (data.size() <= 4) {
+ break;
+ }
+ strm.avail_in = data.size();
+ strm.next_in = (Bytef*)(data.data());
+ if (Z_OK != inflateInit2(&strm, 15 + 32)) {
+ break;
+ }
+ do {
+ sts = false;
+ strm.avail_out = CHUNK_SIZE;
+ strm.next_out = (Bytef*)(out);
+ if (inflate(&strm, Z_NO_FLUSH) < Z_OK) {
+ break;
+ }
+ result.append(out, CHUNK_SIZE - strm.avail_out);
+ sts = true;
+ } while (strm.avail_out == 0);
+ inflateEnd(&strm);
+ } while(false);
+ return sts ? result : QByteArray();
+ {{/contentCompression}}{{^contentCompression}}Q_UNUSED(data);
+ return QByteArray();{{/contentCompression}}
+ }
+
+ QByteArray compress(const QByteArray& input, int level, {{prefix}}CompressionType compressType)
+ {
+ {{#contentCompression}}QByteArray output;
+ static const int GZIP_WINDOW_BIT = 15+16;
+ static const int ZLIB_WINDOW_BIT = 15;
+ static const int CHUNK_SIZE = 8*1024;
+ int windowBits;
+ if (compressType == {{prefix}}CompressionType::Gzip) {
+ windowBits = GZIP_WINDOW_BIT;
+ } else if (compressType == {{prefix}}CompressionType::Zlib) {
+ windowBits = ZLIB_WINDOW_BIT;
+ }
+ do {
+ int flush = 0, ret = 0;
+ bool error_sts = false;
+ z_stream strm{};
+ if (input.length() <= 0) {
+ break;
+ }
+ if (deflateInit2(&strm, qMax(-1, qMin(9, level)), Z_DEFLATED, windowBits, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
+ break;
+ }
+ output.clear();
+ auto input_data = input.data();
+ int input_data_left = input.length();
+ do {
+ int chunk_size = qMin(CHUNK_SIZE, input_data_left);
+ strm.next_in = (unsigned char*)input_data;
+ strm.avail_in = chunk_size;
+ input_data += chunk_size;
+ input_data_left -= chunk_size;
+ flush = (input_data_left <= 0 ? Z_FINISH : Z_NO_FLUSH);
+ do {
+ char out[CHUNK_SIZE];
+ strm.next_out = (unsigned char*)out;
+ strm.avail_out = CHUNK_SIZE;
+ ret = deflate(&strm, flush);
+ if (ret == Z_STREAM_ERROR) {
+ error_sts = true;
+ break;
+ }
+ auto have = (CHUNK_SIZE - strm.avail_out);
+ if (have > 0) {
+ output.append((char*)out, have);
+ }
+ } while (strm.avail_out == 0);
+ } while ((flush != Z_FINISH) && !(error_sts));
+ deflateEnd(&strm);
+ } while(false);
+ return output;
+ {{/contentCompression}}{{^contentCompression}}Q_UNUSED(input);
+ Q_UNUSED(level);
+ Q_UNUSED(compressType);
+ return QByteArray();{{/contentCompression}}
+ }
+ } // namespace {{prefix}}HttpRequestWorker
+
+
+
+ {{#cppNamespaceDeclarations}}
+ } // namespace {{this}}
+ {{/cppNamespaceDeclarations}}