-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrequestmanager.cpp
84 lines (64 loc) · 2.19 KB
/
requestmanager.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
#include "requestmanager.h"
#include <QDebug>
#include <cstdio>
using namespace std;
RequestManager::RequestManager(QObject *parent)
: QObject(parent)
{
response = "";
}
bool RequestManager::request(QUrl aUrl)
{
url = aUrl;
QNetworkRequest request(url);
currentDownload = manager.get(request);
connect(currentDownload, SIGNAL(readyRead()),
SLOT(requestReadyRead()));
connect(currentDownload, SIGNAL(finished()),
SLOT(requestFinished()));
return true;
}
void RequestManager::requestFinished()
{
if (currentDownload->error()) {
qWarning() << "Request Error: " << currentDownload->errorString();
} else {
// check if it was a redirect
if (isHttpRedirect()) {
reportRedirect();
response = "";
QUrl lastUrl = currentDownload->request().url();
currentDownload->deleteLater();
if (lastUrl != url)
request(url);
return;
}
}
currentDownload->deleteLater();
emit finished();
}
void RequestManager::requestReadyRead()
{
response += currentDownload->readAll();
}
bool RequestManager::isHttpRedirect() const
{
int statusCode = currentDownload->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
return statusCode == 301 || statusCode == 302 || statusCode == 303
|| statusCode == 305 || statusCode == 307 || statusCode == 308;
}
void RequestManager::reportRedirect()
{
int statusCode = currentDownload->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
QUrl requestUrl = currentDownload->request().url();
qWarning() << "Request: " << requestUrl.toDisplayString()
<< " was redirected with code: " << statusCode;
QVariant target = currentDownload->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (!target.isValid())
return;
QUrl redirectUrl = target.toUrl();
if (redirectUrl.isRelative())
redirectUrl = requestUrl.resolved(redirectUrl);
qWarning() << "Redirected to: " << redirectUrl.toDisplayString();
url = redirectUrl;
}