KanoopProtocolQt 1.2.3
Qt HTTP operations and MQTT client library
Loading...
Searching...
No Matches
httpoperation.h
1#ifndef HTTPOPERATION_H
2#define HTTPOPERATION_H
3#include <Kanoop/utility/abstractthreadclass.h>
4#include <Kanoop/http/httpheaders.h>
5
6#include <QNetworkCookie>
7#include <QNetworkReply>
8#include <Kanoop/kanoopprotocol.h>
9
10class QNetworkAccessManager;
11/** @brief Base class for HTTP operations executed asynchronously on a dedicated thread. */
12class LIBKANOOPPROTOCOL_EXPORT HttpOperation : public AbstractThreadClass
13{
14 Q_OBJECT
15public:
16 /** @brief Enumeration of supported HTTP request methods. */
18 UnknownMethod = 0x0000, /**< @brief Unknown or uninitialized request method. */
19 Get = 0x0001, /**< @brief HTTP GET method. */
20 Put = 0x0002, /**< @brief HTTP PUT method. */
21 Delete = 0x0004, /**< @brief HTTP DELETE method. */
22 Post = 0x0008, /**< @brief HTTP POST method. */
23 Head = 0x0010, /**< @brief HTTP HEAD method. */
24 Patch = 0x0040, /**< @brief HTTP PATCH method. */
25 MultipartUpload = 0x1000, /**< @brief Multipart file upload method. */
26 };
27
28protected:
29 /** @brief Construct an HTTP operation for the given URL and request method.
30 * @param url The target URL for the operation.
31 * @param method The HTTP request method to use. */
32 HttpOperation(const QString& url, RequestMethod method/* = UnknownMethod*/);
33
34public:
35 /** @brief Destructor. */
36 virtual ~HttpOperation();
37
38 /** @brief Return the target URL of this operation.
39 * @return The URL string. */
40 QString url() const { return _url; }
41
42 /** @brief Return the known HTTP headers set on this operation.
43 * @return The known headers map. */
44 HttpKnownHeaders headers() const { return _headers; }
45
46 /** @brief Return the custom HTTP headers set on this operation.
47 * @return The custom headers map. */
48 HttpCustomHeaders customHeaders() const { return _customHeaders; }
49
50 /** @brief Append a known HTTP header to the request.
51 * @param type The known header type.
52 * @param value The header value. */
53 void appendHeader(QNetworkRequest::KnownHeaders type, const QByteArray& value) { _headers.insert(type, value); }
54
55 /** @brief Append a custom HTTP header to the request.
56 * @param headerName The custom header name.
57 * @param value The header value. */
58 void appendHeader(const QString& headerName, const QByteArray& value) { _customHeaders.insert(headerName, value); }
59
60 /** @brief Abort the running HTTP operation. */
62
63 /** @brief Return the cookies to be sent with the request.
64 * @return The list of request cookies. */
65 QList<QNetworkCookie> requestCookies() const { return _requestCookies; }
66
67 /** @brief Set the cookies to be sent with the request.
68 * @param value The list of cookies. */
69 void setRequestCookies(const QList<QNetworkCookie>& value) { _requestCookies = value; }
70
71 /** @brief Return the cookies received in the response.
72 * @return The list of response cookies. */
73 QList<QNetworkCookie> responseCookies() const { return _responseCookies; }
74
75 /** @brief Return whether peer SSL certificate verification is enabled.
76 * @return True if peer verification is enabled. */
77 bool isVerifyPeer() const { return _verifyPeer; }
78
79 /** @brief Enable or disable peer SSL certificate verification.
80 * @param value True to verify the peer certificate. */
81 void setVerifyPeer(bool value) { _verifyPeer = value; }
82
83 /** @brief Return whether self-signed certificate errors are being ignored.
84 * @return True if self-signed certificate errors are ignored. */
86
87 /** @brief Configure the operation to ignore self-signed certificate errors. */
89
90 /** @brief Return the transfer timeout duration.
91 * @return The transfer timeout as a TimeSpan. */
92 TimeSpan transferTimeout() const { return _transferTimeout; }
93
94 /** @brief Set the transfer timeout duration.
95 * @param value The timeout as a TimeSpan. */
96 void setTransferTimeout(const TimeSpan& value) { _transferTimeout = value; }
97
98 /** @brief Return the network error from the completed operation.
99 * @return The QNetworkReply::NetworkError code. */
100 QNetworkReply::NetworkError networkError() const { return _networkError; }
101
102 /** @brief Return the HTTP reason phrase from the response.
103 * @return The reason phrase string. */
104 QString reasonPhrase() const { return _reasonPhrase; }
105
106 /** @brief Return the response body data.
107 * @return The response body as a byte array. */
108 QByteArray responseBody() const { return _responseBody; }
109
110 /** @brief Return the HTTP status code from the response.
111 * @return The status code integer. */
112 int statusCode() const { return _statusCode; }
113
114 /** @brief Return the wall-clock duration of the HTTP operation.
115 * @return The duration as a TimeSpan. */
116 TimeSpan duration() const { return _duration; }
117
118 /** @brief Return a human-readable string for this operation's request method.
119 * @return The request method string. */
120 QString getRequestMethodString() const { return _RequestMethodToStringMap.getString(_method); }
121
122 /** @brief Return whether this operation uses HTTPS.
123 * @return True if the URL scheme is HTTPS. */
124 bool isHttps() const;
125
126 /** @brief Return a human-readable string for the given request method.
127 * @param method The request method to convert.
128 * @return The request method string. */
129 static QString getRequestMethodString(RequestMethod method) { return _RequestMethodToStringMap.getString(method); }
130
131protected:
132 /** @brief A simple key-value pair used for HTTP parameters. */
133 class KeyValuePair : public QPair<QString, QString>
134 {
135 public:
136 /** @brief Construct an empty key-value pair. */
138
139 /** @brief Construct a key-value pair with the given key and value.
140 * @param key The parameter key.
141 * @param value The parameter value. */
142 KeyValuePair(const QString& key, const QString& value)
143 {
144 first = key;
145 second = value;
146 }
147 };
148
149 /** @brief Execute the HTTP operation (implemented by subclasses). */
150 virtual void execute() = 0;
151
152 /** @brief Hook called after the network reply is received. */
153 virtual void postReplyHook(QNetworkReply*) {}
154
155 /** @brief Set the target URL of this operation.
156 * @param value The URL string. */
157 void setUrl(const QString& value) { _url = value; }
158
159 /** @brief Return the shared network access manager, creating it if necessary.
160 * @return A pointer to the QNetworkAccessManager. */
161 QNetworkAccessManager* networkAccessManager();
162
163 /** @brief Store the network reply and connect its signals.
164 * @param reply The network reply to track. */
165 void setReply(QNetworkReply* reply);
166
167 /** @brief Append all configured headers to the given network request.
168 * @param request The network request to modify. */
169 void appendHeadersToRequest(QNetworkRequest* request);
170
171 /** @brief Configure SSL settings on the given network request.
172 * @param request The network request to configure. */
173 void configureSsl(QNetworkRequest* request);
174
175 /** @brief Called when the operation thread finishes. */
176 virtual void threadFinished() override;
177
178private:
179 virtual void threadStarted() override;
180
181 QString _url;
182 RequestMethod _method;
183
184 HttpKnownHeaders _headers;
185 HttpCustomHeaders _customHeaders;
186 QList<QNetworkCookie> _requestCookies;
187
188 int _statusCode = 0;
189 QNetworkReply::NetworkError _networkError = QNetworkReply::UnknownServerError;
190 QString _reasonPhrase;
191 QByteArray _responseBody;
192 QList<QNetworkCookie> _responseCookies;
193
194 QList<QSslError::SslError> _ignoreSslErrors;
195
196 bool _verifyPeer = true;
197
198 QDateTime _operationStartTime;
199 TimeSpan _transferTimeout = TimeSpan::fromMilliseconds(QNetworkRequest::DefaultTransferTimeoutConstant);
200 TimeSpan _duration;
201
202 QNetworkAccessManager* _networkAccessManager = nullptr;
203 QNetworkReply* _reply = nullptr;
204
205 class RequestMethodToStringMap : public KANOOP::EnumToStringMap<RequestMethod>
206 {
207 public:
208 RequestMethodToStringMap()
209 {
210 insert(UnknownMethod, "UnknownMethod");
211 insert(Get, "GET");
212 insert(Put, "PUT");
213 insert(Delete, "DELETE");
214 insert(Post, "POST");
215 insert(Head, "HEAD");
216 insert(Patch, "PATCH");
217 insert(MultipartUpload, "UPLOAD");
218 }
219 };
220
221 static const RequestMethodToStringMap _RequestMethodToStringMap;
222 static const QList<QSslError::SslError> SelfSignedCertificateErrors;
223
224signals:
225 /** @brief Emitted when the HTTP operation has completed. */
227
228protected slots:
229 /** @brief Handle the network reply finished signal. */
231
232 /** @brief Handle SSL errors from the network reply.
233 * @param errors The list of SSL errors encountered. */
234 void onSslErrors(const QList<QSslError> &errors);
235
236 /** @brief Handle a network error from the reply.
237 * @param error The network error code. */
238 void onReplyError(QNetworkReply::NetworkError error);
239};
240
241#endif // HTTPOPERATION_H
Map of custom HTTP header names to their values.
Definition httpheaders.h:10
Map of Qt known HTTP headers to their values.
Definition httpheaders.h:15
A simple key-value pair used for HTTP parameters.
KeyValuePair()
Construct an empty key-value pair.
KeyValuePair(const QString &key, const QString &value)
Construct a key-value pair with the given key and value.
Base class for HTTP operations executed asynchronously on a dedicated thread.
TimeSpan transferTimeout() const
Return the transfer timeout duration.
QNetworkAccessManager * networkAccessManager()
Return the shared network access manager, creating it if necessary.
HttpOperation(const QString &url, RequestMethod method)
Construct an HTTP operation for the given URL and request method.
void setRequestCookies(const QList< QNetworkCookie > &value)
Set the cookies to be sent with the request.
void appendHeader(QNetworkRequest::KnownHeaders type, const QByteArray &value)
Append a known HTTP header to the request.
QList< QNetworkCookie > requestCookies() const
Return the cookies to be sent with the request.
QString getRequestMethodString() const
Return a human-readable string for this operation's request method.
void appendHeadersToRequest(QNetworkRequest *request)
Append all configured headers to the given network request.
virtual void threadFinished() override
Called when the operation thread finishes.
void operationComplete()
Emitted when the HTTP operation has completed.
void setUrl(const QString &value)
Set the target URL of this operation.
static QString getRequestMethodString(RequestMethod method)
Return a human-readable string for the given request method.
QNetworkReply::NetworkError networkError() const
Return the network error from the completed operation.
void abortOperation()
Abort the running HTTP operation.
HttpKnownHeaders headers() const
Return the known HTTP headers set on this operation.
void appendHeader(const QString &headerName, const QByteArray &value)
Append a custom HTTP header to the request.
void setReply(QNetworkReply *reply)
Store the network reply and connect its signals.
virtual void postReplyHook(QNetworkReply *)
Hook called after the network reply is received.
HttpCustomHeaders customHeaders() const
Return the custom HTTP headers set on this operation.
int statusCode() const
Return the HTTP status code from the response.
void onSslErrors(const QList< QSslError > &errors)
Handle SSL errors from the network reply.
QByteArray responseBody() const
Return the response body data.
virtual void execute()=0
Execute the HTTP operation (implemented by subclasses).
void configureSsl(QNetworkRequest *request)
Configure SSL settings on the given network request.
virtual ~HttpOperation()
Destructor.
bool isVerifyPeer() const
Return whether peer SSL certificate verification is enabled.
QString url() const
Return the target URL of this operation.
bool isHttps() const
Return whether this operation uses HTTPS.
void ignoreSelfSignedCertificate()
Configure the operation to ignore self-signed certificate errors.
RequestMethod
Enumeration of supported HTTP request methods.
QString reasonPhrase() const
Return the HTTP reason phrase from the response.
void setTransferTimeout(const TimeSpan &value)
Set the transfer timeout duration.
void onReplyError(QNetworkReply::NetworkError error)
Handle a network error from the reply.
bool isSelfSignedCertificateErrorIgnored() const
Return whether self-signed certificate errors are being ignored.
void setVerifyPeer(bool value)
Enable or disable peer SSL certificate verification.
TimeSpan duration() const
Return the wall-clock duration of the HTTP operation.
void onReplyFinished()
Handle the network reply finished signal.
QList< QNetworkCookie > responseCookies() const
Return the cookies received in the response.