-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpRequestWorker.cpp
executable file
·458 lines (400 loc) · 14.3 KB
/
HttpRequestWorker.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/****************************************************************************
**
** Copyright (C) 2007-2015 Speedovation
** Copyright (C) 2015 creativepulse.gr
** Contact: Speedovation Lab (info@speedovation.com)
**
** KineticWing IDE CrashHandler
** http:// kineticwing.com
** This file is part of the core classes of the KiWi Editor (IDE)
**
** Author: creativepulse.gr
** https://github.com/codeyash
** https://github.com/fro0m
** License : Apache License 2.0
**
** All rights are reserved.
*/
#include "HttpRequestWorker.h"
#include <QBuffer>
#include <QDateTime>
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QRandomGenerator>
#include <QUrl>
HttpRequestInput::HttpRequestInput(const QString& v_urlStr, const QString& v_httpMethod)
: urlStr(v_urlStr), httpMethod(v_httpMethod), varLayout(NOT_SET)
{}
void HttpRequestInput::addVar(const QString& key, const QByteArray& value)
{
vars[key] = value;
}
void HttpRequestInput::addHeader(const QByteArray& header, const QByteArray& value)
{
headers[header] = value;
}
void HttpRequestInput::addFile(const QString& variableName, const QString& localFilename,
const QString& requestFilename, const QByteArray& mimeType)
{
HttpRequestInputFilePathElement file;
file.variableName = variableName;
file.localFilename = localFilename;
file.requestFilename = requestFilename;
file.mimeType = mimeType;
files.append(file);
}
void HttpRequestInput::addFile(const QString& variableName,
const QByteArray& localFileData,
const QString& requestFilename, const QByteArray& mimeType)
{
HttpRequestInputFileDataElement file;
file.variableName = variableName;
file.localFileData = localFileData;
file.requestFilename = requestFilename;
file.mimeType = mimeType;
filesData.append(file);
}
HttpRequestWorker::HttpRequestWorker(QObject* parent) : QObject(parent), manager(NULL)
{
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this,
SLOT(managerFinished(QNetworkReply*)));
}
HttpRequestWorker::~HttpRequestWorker()
{}
QByteArray HttpRequestWorker::httpAttributeEncode(const QString& attribute_name,
const QString& input)
{
// result structure follows RFC 5987
bool need_utf_encoding = false;
QString result = "";
QByteArray input_c = input.toLocal8Bit();
char c;
for (int i = 0; i < input_c.length(); i++)
{
c = input_c.at(i);
if (c == '\\' || c == '/' || c == '\0' || c < ' ' || c > '~')
{
// ignore and request utf-8 version
need_utf_encoding = true;
}
else if (c == '"')
{
result += "\\\"";
}
else
{
result += c;
}
}
if (result.length() == 0)
{
need_utf_encoding = true;
}
if (!need_utf_encoding)
{
// return simple version
return QString("%1=\"%2\"").arg(attribute_name, result).toLatin1();
}
QString result_utf8 = "";
for (int i = 0; i < input_c.length(); i++)
{
c = input_c.at(i);
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
{
result_utf8 += c;
}
else
{
result_utf8 +=
"%" +
QString::number(static_cast<unsigned char>(input_c.at(i)), 16).toUpper();
}
}
// return enhanced version with UTF-8 support
return QString("%1=\"%2\"; %1*=utf-8''%3")
.arg(attribute_name, result, result_utf8)
.toLatin1();
}
QNetworkReply::NetworkError HttpRequestWorker::execute(HttpRequestInput* input)
{
// reset variables
QByteArray requestContent = "";
response = "";
errorType = QNetworkReply::NoError;
errorStr = "";
// decide on the variable layout
if (input->files.length() > 0 || input->filesData.length() > 0)
{
input->varLayout = MULTIPART;
}
else if (input->varLayout == NOT_SET)
{
input->varLayout = input->httpMethod == Literals::getMethod ||
input->httpMethod == Literals::headMethod
? ADDRESS
: URL_ENCODED;
}
// prepare request content
QByteArray boundary = "";
if (input->varLayout == ADDRESS || input->varLayout == URL_ENCODED)
{
// variable layout is ADDRESS or URL_ENCODED
if (input->vars.count() > 0)
{
bool first = true;
foreach (QString key, input->vars.keys())
{
if (!first)
{
requestContent.append("&");
}
first = false;
requestContent.append(QUrl::toPercentEncoding(key));
requestContent.append("=");
requestContent.append(QUrl::toPercentEncoding(input->vars.value(key)));
}
if (input->varLayout == ADDRESS)
{
input->urlStr += "?" + requestContent;
requestContent = "";
}
}
}
else if (input->varLayout == MULTIPART)
{
// variable layout is MULTIPART
boundary = "__-----------------------" +
QString::number(QDateTime::currentSecsSinceEpoch()).toLatin1() +
QString::number(QRandomGenerator::system()->generate()).toLatin1();
QByteArray boundaryDelimiter = "--";
QByteArray newLine = "\r\n";
// add variables
foreach (QString key, input->vars.keys())
{
// add boundary
requestContent.append(boundaryDelimiter);
requestContent.append(boundary);
requestContent.append(newLine);
// add header
//! The Content-Disposition response-header field has been proposed
//! as a means for the origin server to suggest a default filename
//! if the user requests that the content is saved to a file. This
//! usage is derived from the definition of Content-Disposition
//! in RFC 1806
requestContent.append("Content-Disposition: form-data; ");
requestContent.append(httpAttributeEncode("name", key));
requestContent.append(newLine);
requestContent.append("Content-Type: text/plain");
requestContent.append(newLine);
// add header to body splitter
requestContent.append(newLine);
// add variable content
requestContent.append(input->vars.value(key));
requestContent.append(newLine);
}
// add files from paths
for (QList<HttpRequestInputFilePathElement>::iterator fileInfo =
input->files.begin();
fileInfo != input->files.end(); ++fileInfo)
{
QFileInfo fi(fileInfo->localFilename);
// ensure necessary variables are available
if (
fileInfo->localFilename
.isEmpty() ||
fileInfo->variableName.isEmpty() ||
!fi.exists() || !fi.isFile() || !fi.isReadable())
{
// silent abort for the current file
qDebug() << "problem with file in request";
continue;
}
QFile file(fileInfo->localFilename);
if (!file.open(QIODevice::ReadOnly))
{
// silent abort for the current file
continue;
}
// ensure filename for the request
if (/*fileInfo->requestFilename == NULL ||*/ fileInfo->requestFilename
.isEmpty())
{
fileInfo->requestFilename = fi.fileName();
if (fileInfo->requestFilename.isEmpty())
{
fileInfo->requestFilename = "file";
}
}
// add boundary
requestContent.append(boundaryDelimiter);
requestContent.append(boundary);
requestContent.append(newLine);
// add header
requestContent.append(
QString("Content-Disposition: form-data; %1; %2")
.arg(httpAttributeEncode("name", fileInfo->variableName),
httpAttributeEncode("filename", fileInfo->requestFilename))
.toLatin1());
requestContent.append(newLine);
if (!(fileInfo->mimeType.isNull() || fileInfo->mimeType.isEmpty()))
{
requestContent.append("Content-Type: ");
requestContent.append(fileInfo->mimeType);
requestContent.append(newLine);
}
requestContent.append("Content-Transfer-Encoding: binary");
requestContent.append(newLine);
// add header to body splitter
requestContent.append(newLine);
// add file content
requestContent.append(file.readAll());
requestContent.append(newLine);
file.close();
}
// add files from files data
for (QList<HttpRequestInputFileDataElement>::iterator fileInfo =
input->filesData.begin();
fileInfo != input->filesData.end(); ++fileInfo)
{
// ensure necessary variables are available
if (fileInfo->localFileData.isEmpty() ||
fileInfo->variableName.isEmpty())
{
// silent abort for the current file
qDebug() << "problem with file in request";
continue;
}
// ensure filename for the request
if (fileInfo->requestFilename.isEmpty())
{
fileInfo->requestFilename = "file";
}
// add boundary
requestContent.append(boundaryDelimiter);
requestContent.append(boundary);
requestContent.append(newLine);
// add header
requestContent.append(
QString("Content-Disposition: form-data; %1; %2")
.arg(httpAttributeEncode("name", fileInfo->variableName),
httpAttributeEncode("filename", fileInfo->requestFilename))
.toLatin1());
requestContent.append(newLine);
if (!(fileInfo->mimeType.isNull() || fileInfo->mimeType.isEmpty()))
{
requestContent.append("Content-Type: ");
requestContent.append(fileInfo->mimeType);
requestContent.append(newLine);
}
requestContent.append("Content-Transfer-Encoding: binary");
requestContent.append(newLine);
// add header to body splitter
requestContent.append(newLine);
// add file content
requestContent.append(fileInfo->localFileData);
requestContent.append(newLine);
}
// add end of body
requestContent.append(boundaryDelimiter);
requestContent.append(boundary);
requestContent.append(boundaryDelimiter);
}
else // JSON case
{
QJsonObject requestContentObj;
QMapIterator<QString, QByteArray> it{input->vars};
while (it.hasNext())
{
it.next();
QJsonDocument currentDoc = QJsonDocument::fromJson(it.value());
if (currentDoc.isObject())
requestContentObj[it.key()] = currentDoc.object();
else if (currentDoc.isArray())
requestContentObj[it.key()] = currentDoc.array();
else
requestContentObj[it.key()] = QString(it.value());
}
QJsonDocument requestContentDoc;
requestContentDoc.setObject(requestContentObj);
requestContent.append(requestContentDoc.toJson(QJsonDocument::Compact));
}
// prepare connection
QUrl url;
url.setUrl(input->urlStr);
QNetworkRequest request = QNetworkRequest(url);
request.setHeader(QNetworkRequest::UserAgentHeader, "Frumkin K. E. REST Client");
if (input->varLayout == URL_ENCODED)
{
request.setHeader(QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
}
else if (input->varLayout == JSON)
{
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
}
else if (input->varLayout == MULTIPART)
{
request.setHeader(QNetworkRequest::ContentTypeHeader,
"multipart/form-data; boundary=" + boundary);
}
//! add custom headers
foreach (const QByteArray& key, input->headers.keys())
{
request.setRawHeader(key, input->headers[key]);
}
QNetworkReply* reply;
if (input->httpMethod == Literals::getMethod)
{
reply = manager->get(request);
}
else if (input->httpMethod == Literals::postMethod)
{
qWarning() << requestContent;
reply = manager->post(request, requestContent);
}
else if (input->httpMethod == Literals::putMethod)
{
reply = manager->put(request, requestContent);
}
else if (input->httpMethod == Literals::headMethod)
{
reply = manager->head(request);
}
else if (input->httpMethod == Literals::deleteMethod)
{
reply = manager->deleteResource(request);
}
else
{
QBuffer buff(&requestContent);
reply = manager->sendCustomRequest(request, input->httpMethod.toLatin1(), &buff);
}
return reply->error();
}
void HttpRequestWorker::setReadResponseOnError(bool t_readResponseOnError)
{
m_readResponseOnError = t_readResponseOnError;
}
void HttpRequestWorker::setReadErrorString(bool readErrorString)
{
m_readErrorString = readErrorString;
}
void HttpRequestWorker::managerFinished(QNetworkReply* reply)
{
statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
errorType = reply->error();
if (errorType == QNetworkReply::NoError || m_readResponseOnError)
{
response = reply->readAll();
}
if (m_readErrorString)
{
errorStr = reply->errorString();
}
reply->deleteLater();
emit executionFinished(this);
}