| Version: 3.2.8

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.

Instances of wxWebRequest are created by using wxWebSession::CreateRequest().

The requests are handled asynchronously and event handlers are used to communicate the request status. 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:796
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:132
wxWebRequest::State_Failed
@ State_Failed
The request failed.
Definition: webrequest.h:177
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:843

# 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

## 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...
Request options
Methods that set options before starting the request
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 (wxInputStream *dataStream, const wxString &contentType, wxFileOffset dataSize=wxInvalidOffset)
| Set the binary data to be posted to the server. More...
void | SetStorage (Storage storage)
| Sets how response data will be stored. More...
void | DisablePeerVerify (bool disable=true)
| Disable SSL certificate verification. More...
bool | IsPeerVerifyDisabled () const
| Returns if peer verification has been disabled. 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

## ◆ 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.

## ◆ 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 NULL.

## ◆ 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

Returns if peer verification has been disabled.

See also
  DisablePeerVerify()

## ◆ SetData() [1/2]

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/2]

bool wxWebRequest::SetData | ( | 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.release(), "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 NULL, 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.

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