#include <wx/webrequest.h>
This class allows for simple HTTP requests using the operating system's components as implementation.
The latest features of the operating system will be used if available (e.g. HTTP/2, TLS 1.3). System-wide configuration like proxy and SSL certificates will be used when possible.
Instances of wxWebRequest are created by using wxWebSession::CreateRequest().
The requests are handled asynchronously and event handlers are used to communicate the request status. See wxWebRequestSync for a class that can be used to perform synchronous requests.
The response data may be stored in memory, to a file or processed directly, see SetStorage() for details.
Example usage in an event handler function of some window (i.e. this
in the example below is a wxWindow pointer):
The location of where files are downloaded can also be defined prior to any request by passing unique IDs to wxWebSession::GetDefault().CreateRequest()
and processing them in your wxEVT_WEBREQUEST_STATE
handler. For example, create a map of IDs with their respective download paths prior to creating any requests. For each call to wxWebSession::GetDefault().CreateRequest()
, pass in the webpath to download and an ID from your map. Then, in your wxEVT_WEBREQUEST_STATE
handler, get the ID from the wxWebRequestEvent
object and look it up from your ID map. Here, you can access the download path that you assigned to this ID and proceed to save the file to that location.
Starting with macOS 10.11 and iOS 9 an application cannot create insecure connections (this includes HTTP and unverified HTTPS). You have to include additional fields in your Info.plist to enable such connections. For further details see the documentation on NSAppTransportSecurity here
The following APIs are used per platform, additional details about supported features may be found in their documentation.
Available features by implementation and minimum version:
Operating System | API | HTTPS | HTTP/2 |
---|---|---|---|
Windows | WinHTTP | Yes | Windows 10 1607 |
macOS | NSURLSession | macOS 10.9 | macOS 10.11 |
iOS | NSURLSession | iOS 7.0 | iOS 9.0 |
Linux | libcurl | Yes | 7.47.0 |
The following event handler macros redirect the events to member function handlers 'func' with prototypes like:
Event macros for events emitted by this class:
Request options | |
enum | { Ignore_Certificate = 1 , Ignore_Host = 2 , Ignore_All = Ignore_Certificate | Ignore_Host } |
Flags for disabling security features. More... | |
void | SetHeader (const wxString &name, const wxString &value) |
Sets a request header which will be sent to the server by this request. More... | |
void | SetMethod (const wxString &method) |
Set common or expanded HTTP method. More... | |
void | SetData (const wxString &text, const wxString &contentType, const wxMBConv &conv=wxConvUTF8) |
Set the text to be posted to the server. More... | |
bool | SetData (std::unique_ptr< wxInputStream > dataStream, const wxString &contentType, wxFileOffset dataSize=wxInvalidOffset) |
Set the binary data to be posted to the server. More... | |
bool | SetData (wxInputStream *dataStream, const wxString &contentType, wxFileOffset dataSize=wxInvalidOffset) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More... | |
void | SetStorage (Storage storage) |
Sets how response data will be stored. More... | |
void | MakeInsecure (int flags=Ignore_All) |
Make connection insecure by disabling security checks. More... | |
void | DisablePeerVerify (bool disable=true) |
Disable SSL certificate verification. More... | |
bool | IsPeerVerifyDisabled () const |
Return true if SSL certificate verification has been disabled. More... | |
Public Types | |
enum | State { State_Idle , State_Unauthorized , State_Active , State_Completed , State_Failed , State_Cancelled } |
Possible request states returned by GetState(). More... | |
enum | Storage { Storage_Memory , Storage_File , Storage_None } |
Possible storage types. More... | |
Public Member Functions | |
wxWebRequest () | |
Default constructor creates an invalid object. More... | |
bool | IsOk () const |
Check if the object is valid. More... | |
wxWebRequestHandle | GetNativeHandle () const |
Return the native handle corresponding to this request object. More... | |
void | Start () |
Send the request to the server asynchronously. More... | |
void | Cancel () |
Cancel an active request. More... | |
wxWebResponse | GetResponse () const |
Returns a response object after a successful request. More... | |
wxWebAuthChallenge | GetAuthChallenge () const |
Returns the current authentication challenge object while the request is in State_Unauthorized . More... | |
int | GetId () const |
Returns the id specified while creating this request. More... | |
Progress methods | |
Methods that describe the requests progress | |
State | GetState () const |
Returns the current state of the request. More... | |
wxFileOffset | GetBytesSent () const |
Returns the number of bytes sent to the server. More... | |
wxFileOffset | GetBytesExpectedToSend () const |
Returns the total number of bytes expected to be sent to the server. More... | |
wxFileOffset | GetBytesReceived () const |
Returns the number of bytes received from the server. More... | |
wxFileOffset | GetBytesExpectedToReceive () const |
Returns the number of bytes expected to be received from the server. More... | |
anonymous enum |
Flags for disabling security features.
enum wxWebRequest::State |
Possible request states returned by GetState().
Enumerator | |
---|---|
State_Idle | The request has just been created and Start() has not been called. |
State_Unauthorized | The request is currently unauthorized. Calling GetAuthChallenge() returns a challenge object with further details and calling SetCredentials() on this object will retry the request using these credentials. |
State_Active | The request is about to start. An event notifying about the switch to this state is generated when Start() is called (unless an error occurs, in which case the state becomes State_Failed instead). Handling this event allows to do something right before the asynchronous request actually starts. |
State_Completed | The request completed successfully and all data has been received. The HTTP status code returned by wxWebResponse::GetStatus() will be in 100-399 range, and typically 200. |
State_Failed | The request failed. This can happen either because the request couldn't be performed at all (e.g. a connection error) or if the server returned an HTTP error. In the former case wxWebResponse::GetStatus() returns 0, while in the latter it returns a value in 400-599 range. |
State_Cancelled | The request has been cancelled before completion by calling Cancel() |
Possible storage types.
Set by SetStorage().
Enumerator | |
---|---|
Storage_Memory | All data is collected in memory until the request is complete. It can be later retrieved using wxWebResponse::AsString() or wxWebResponse::GetStream(). |
Storage_File | The data is written to a file on disk as it is received. This file can be later read from using wxWebResponse::GetStream() or otherwise processed using wxWebRequestEvent::GetDataFile(). |
Storage_None | The data is not stored by the request and is only available via events. Data can be retrieved using wxWebRequestEvent::GetDataBuffer() and wxWebRequestEvent::GetDataSize() methods from wxEVT_WEBREQUEST_DATA handler. |
wxWebRequest::wxWebRequest | ( | ) |
Default constructor creates an invalid object.
Initialize it by assigning wxWebSession::CreateRequest() to it before using it.
void wxWebRequest::Cancel | ( | ) |
Cancel an active request.
Note that cancelling is asynchronous, so the application needs to wait until the request state becomes State_Cancelled
to know when the request was really cancelled.
Request must be active when Cancel() is called, i.e. the current state can't be State_Idle
. However, because it can be difficult to avoid doing it in some circumstances, Cancel() may be called multiple times and only a single wxWebRequestEvent will be sent even in this case.
void wxWebRequest::DisablePeerVerify | ( | bool | disable = true | ) |
Disable SSL certificate verification.
This can be used to connect to self signed servers or other invalid SSL connections. Disabling verification makes the communication insecure.
wxWebAuthChallenge wxWebRequest::GetAuthChallenge | ( | ) | const |
Returns the current authentication challenge object while the request is in State_Unauthorized
.
wxFileOffset wxWebRequest::GetBytesExpectedToReceive | ( | ) | const |
Returns the number of bytes expected to be received from the server.
This value is based on the Content-Length
header, if none is found it will return -1.
wxFileOffset wxWebRequest::GetBytesExpectedToSend | ( | ) | const |
Returns the total number of bytes expected to be sent to the server.
This value stays unchanged throughout the request duration.
wxFileOffset wxWebRequest::GetBytesReceived | ( | ) | const |
Returns the number of bytes received from the server.
This value grows monotonically from 0 to GetBytesExpectedToReceive() (unless it is unknown).
wxFileOffset wxWebRequest::GetBytesSent | ( | ) | const |
Returns the number of bytes sent to the server.
This value grows monotonically from 0 to GetBytesExpectedToSend().
int wxWebRequest::GetId | ( | ) | const |
Returns the id specified while creating this request.
wxWebRequestHandle wxWebRequest::GetNativeHandle | ( | ) | const |
Return the native handle corresponding to this request object.
wxWebRequestHandle
is an opaque type containing a value of the following type according to the backend being used:
HINTERNET
request handle.CURL
struct pointer.NSURLSessionTask
object pointer.Note that this function returns a valid value only after the request is started successfully using Start(). Notably, it is guaranteed to return a valid value when handling wxWebRequestEvent corresponding to the switch to State_Active
.
wxWebResponse wxWebRequest::GetResponse | ( | ) | const |
Returns a response object after a successful request.
Before sending a request or after a failed request this will return an invalid response object, i.e. such that wxWebResponse::IsOk() returns false
.
State wxWebRequest::GetState | ( | ) | const |
Returns the current state of the request.
bool wxWebRequest::IsOk | ( | ) | const |
Check if the object is valid.
If the object is invalid, it must be assigned a valid request before any other methods can be used (with the exception of GetNativeHandle()).
bool wxWebRequest::IsPeerVerifyDisabled | ( | ) | const |
Return true if SSL certificate verification has been disabled.
void wxWebRequest::MakeInsecure | ( | int | flags = Ignore_All | ) |
Make connection insecure by disabling security checks.
Don't use this function unless absolutely necessary as disabling the security checks makes the communication insecure by allowing man-in-the-middle attacks.
By default, all security checks are enabled. Passing 0 as flags (re-)enables all security checks and makes the connection secure again.
Please note that under macOS this function always disables all the security checks if any of them is disabled, i.e. it is not possible to skip just the certificate or just the host name verification.
void wxWebRequest::SetData | ( | const wxString & | text, |
const wxString & | contentType, | ||
const wxMBConv & | conv = wxConvUTF8 |
||
) |
Set the text to be posted to the server.
After a successful call to this method, the request will use HTTP POST
instead of the default GET
when it's executed.
text | The text data to post. |
contentType | The value of HTTP "Content-Type" header, e.g. "text/html; charset=UTF-8". |
conv | Conversion used when sending the text to the server |
bool wxWebRequest::SetData | ( | std::unique_ptr< wxInputStream > | dataStream, |
const wxString & | contentType, | ||
wxFileOffset | dataSize = wxInvalidOffset |
||
) |
Set the binary data to be posted to the server.
The next request will be a HTTP POST
instead of the default HTTP GET
and the given dataStream will be posted as the body of this request.
Example of use:
dataStream | The data in this stream will be posted as the request body. The pointer may be nullptr, which will result in sending 0 bytes of data, but if not empty, should be valid, i.e. wxInputStream::IsOk() must return true. This object takes ownership of the passed in pointer and will delete it, i.e. the pointer must be heap-allocated. |
contentType | The value of HTTP "Content-Type" header, e.g. "application/octet-stream". |
dataSize | Amount of data which is sent to the server. If set to wxInvalidOffset all stream data is sent. |
bool wxWebRequest::SetData | ( | wxInputStream * | dataStream, |
const wxString & | contentType, | ||
wxFileOffset | dataSize = wxInvalidOffset |
||
) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Sets a request header which will be sent to the server by this request.
The header will be added if it hasn't been set before or replaced otherwise.
name | Name of the header |
value | String value of the header. An empty string will remove the header. |
void wxWebRequest::SetMethod | ( | const wxString & | method | ) |
Set common or expanded HTTP method.
The default method is GET unless request data is provided in which case POST is the default.
method | HTTP method name, e.g. "GET". |
void wxWebRequest::SetStorage | ( | Storage | storage | ) |
Sets how response data will be stored.
The default storage method Storage_Memory
collects all response data in memory until the request is completed. This is fine for most usage scenarios like API calls, loading images, etc. For larger downloads or if the response data will be used permanently Storage_File
instructs the request to write the response to a temporary file. This temporary file may then be read or moved after the request is complete. The file will be downloaded to the system temp directory as returned by wxStandardPaths::GetTempDir(). To specify a different directory use wxWebSession::SetTempDir().
Sometimes response data needs to be processed while its downloaded from the server. For example if the response is in a format that can be parsed piece by piece like XML, JSON or an archive format like ZIP. In these cases storing the data in memory or a file before being able to process it might not be ideal and Storage_None
should be set. With this storage method the data is only available during the wxEVT_WEBREQUEST_DATA
event calls as soon as it's received from the server.
void wxWebRequest::Start | ( | ) |
Send the request to the server asynchronously.
Events will be triggered on success or failure.
The current state must be State_Idle
, already started requests can't be started again.