-
Notifications
You must be signed in to change notification settings - Fork 3
/
httpclient.cpp
56 lines (44 loc) · 1.5 KB
/
httpclient.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
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QTimer>
#include <QEventLoop>
#include "httpclient.hpp"
using namespace Bidstack::Http;
HttpClient::HttpClient(QObject *parent) : QObject(parent) {
m_manager = new QNetworkAccessManager();
}
HttpResponse* HttpClient::send(HttpRequest* request) {
QNetworkRequest networkRequest(request->url());
QMap<QString, QString> headers = request->headers();
foreach (QString key, headers.keys()) {
networkRequest.setRawHeader(
key.toUtf8(),
QString(headers.value(key)).toUtf8()
);
}
QNetworkReply *networkReply;
if (request->method() == "GET") {
networkReply = m_manager->get(networkRequest);
} else if (request->method() == "POST") {
networkReply = m_manager->post(networkRequest, request->body()->toByteArray());
} else {
throw "Unknown or unimplemented HTTP method '" + request->method() + "'";
}
QTimer timer;
QEventLoop loop;
connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
connect(networkReply, SIGNAL(finished()), &loop, SLOT(quit()));
timer.setSingleShot(true);
timer.start(5000); // 5 seconds
loop.exec();
HttpResponse *response;
if (timer.isActive()) {
timer.stop();
response = new HttpResponse(networkReply);
} else {
networkReply->abort();
response = new HttpResponse(500);
}
disconnect(networkReply, SIGNAL(finished()), &loop, SLOT(quit()));
return response;
}