| Version: 3.3.1

Public Types | Public Member Functions | List of all members
wxWebRequest Class Reference
Class List by Category » Networking

`#include <wx/webrequest.h>`

## Detailed Description

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. When using libcurl backend, environment variables `CURL_CA_BUNDLE`, `SSL_CERT_FILE` and `SSL_CERT_DIR` are used to change the trusted certificates location if they are defined.

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):

// Create the request object
wxWebRequest request = wxWebSession::GetDefault().CreateRequest(
this,
"https://www.wxwidgets.org/downloads/logos/blocks.png"
);
if ( !request.IsOk() ) {
// This is not expected, but handle the error somehow.
}
// Bind state event
Bind(wxEVT_WEBREQUEST_STATE, [](wxWebRequestEvent& evt) {
switch (evt.GetState())
{
// Request completed
case wxWebRequest::State_Completed:
{
wxImage logoImage(*evt.GetResponse().GetStream());
if (logoImage.IsOk())
wxLogInfo("Image successfully downloaded");
... do something with it ...
break;
}
// Request failed
case wxWebRequest::State_Failed:
wxLogError("Could not load logo: %s", evt.GetErrorDescription());
break;
}
});
// Start the request
request.Start();
wxWebRequestEvent
A web request event sent during or after server communication.
Definition: webrequest.h:1600
wxWebRequestEvent::GetErrorDescription
const wxString & GetErrorDescription() const
A textual error description for a client side error in case of State_Failed.
wxWebRequestEvent::GetState
wxWebRequest::State GetState() const
Return the current state of the request.
wxWebRequest
This class allows for simple HTTP requests using the operating system's components as implementation.
Definition: webrequest.h:147
wxWebRequest::State_Failed
@ State_Failed
The request failed.
Definition: webrequest.h:192
wxWebRequest::Start
void Start()
Send the request to the server asynchronously.
wxWebRequest::IsOk
bool IsOk() const
Check if the object is valid.
wxWebSession::GetDefault
static wxWebSession & GetDefault()
Returns the default session.
wxWebSession::CreateRequest
wxWebRequest CreateRequest(wxEvtHandler *handler, const wxString &url, int id=wxID_ANY)
Create a new request for the specified URL.
wxLogError
void wxLogError(const char *formatString,...)
The functions to use for error messages, i.e.
wxEVT_WEBREQUEST_STATE
wxEventType wxEVT_WEBREQUEST_STATE
Definition: webrequest.h:1647

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.

# macOS and iOS App Transport Security

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

# Implementation Descriptions

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

## Events emitted by this class

The following event handler macros redirect the events to member function handlers 'func' with prototypes like:

void handlerFuncName(wxWebRequestEvent& event)

Event macros for events emitted by this class:

- wxEVT_WEBREQUEST_STATE(id, func):
  The request state changed.
- wxEVT_WEBREQUEST_DATA(id, func):
  A new block of data has been downloaded.

Since
  3.1.5

##

Library: wxNet
Category: Networking

See also
  wxWebResponse, wxWebSession

## Request options
Methods that set options before starting the request
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...

## Member Enumeration Documentation

## ◆ anonymous enum

anonymous enum

Flags for disabling security features.

Since
  3.3.0

Enumerator
Ignore_Certificate | Disable SSL certificate verification. This can be used to accept self-signed or expired certificates.
Ignore_Host | Disable host name verification. This can be used to accept a valid certificate for a different host than the one it was issued for.
Ignore_All | Disable all security checks for maximum insecurity.

## ◆ State

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()

## ◆ Storage

enum wxWebRequest::Storage

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.

## Constructor & Destructor Documentation

## ◆ wxWebRequest()

wxWebRequest::wxWebRequest | ( |  | ) |

Default constructor creates an invalid object.

Initialize it by assigning wxWebSession::CreateRequest() to it before using it.

See also
  IsOk()

## Member Function Documentation

## ◆ Cancel()

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.

## ◆ DisablePeerVerify()

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.

See also
  MakeInsecure()

## ◆ GetAuthChallenge()

wxWebAuthChallenge wxWebRequest::GetAuthChallenge | ( |  | ) | const

Returns the current authentication challenge object while the request is in `State_Unauthorized`.

## ◆ GetBytesExpectedToReceive()

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.

See also
  wxWebResponse::GetContentLength()

## ◆ GetBytesExpectedToSend()

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.

## ◆ GetBytesReceived()

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).

## ◆ GetBytesSent()

wxFileOffset wxWebRequest::GetBytesSent | ( |  | ) | const

Returns the number of bytes sent to the server.

This value grows monotonically from 0 to GetBytesExpectedToSend().

## ◆ GetId()

int wxWebRequest::GetId | ( |  | ) | const

Returns the id specified while creating this request.

## ◆ GetNativeHandle()

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:

- For WinHTTP backend, this is `HINTERNET` request handle.
- For CURL backend, this is a `CURL` struct pointer.
- For macOS backend, this is `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`.

See also
  wxWebSession::GetNativeHandle()

## ◆ GetResponse()

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`.

## ◆ GetState()

State wxWebRequest::GetState | ( |  | ) | const

Returns the current state of the request.

## ◆ IsOk()

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()).

## ◆ IsPeerVerifyDisabled()

bool wxWebRequest::IsPeerVerifyDisabled | ( |  | ) | const

Return true if SSL certificate verification has been disabled.

See also
  DisablePeerVerify(), GetSecurityFlags()

## ◆ MakeInsecure()

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.

Since
  3.3.0

## ◆ SetData() [1/3]

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.

Parameters

  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

## ◆ SetData() [2/3]

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:

std::unique_ptr<wxInputStream> stream(new wxFileInputStream("some_file.dat"));
if ( !stream->IsOk() ) {
// Handle error (due to e.g. file not found) here.
...
return;
}
request.SetData(stream, "application/octet-stream")
wxFileInputStream
This class represents data read in from a file.
Definition: wfstream.h:229

Parameters

  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.

Returns
  false if dataStream is not-empty but invalid or if dataSize is not specified and the attempt to determine stream size failed; true in all the other cases.

## ◆ SetData() [3/3]

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.

## ◆ SetHeader()

void wxWebRequest::SetHeader | ( | const wxString & | name,
|  | const wxString & | value
| ) |  |

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.

Parameters

  name | Name of the header
  value | String value of the header. An empty string will remove the header.

## ◆ SetMethod()

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.

Parameters

  method | HTTP method name, e.g. "GET".

## ◆ SetStorage()

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.

## ◆ Start()

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.

See also
  Cancel()