| Version: 3.3.1

Classes | Public Types | Public Member Functions | List of all members
wxWebRequestSync Class Reference

`#include <wx/webrequest.h>`

## Detailed Description

This class allows to perform synchronous HTTP requests using the operating components as implementation.

Please note that this class must not be used from the main thread of GUI applications, only use it from worker threads.

Example of use:

auto request = wxWebSessionSync::GetDefault().CreateRequest("https://www.wxwidgets.org");
auto result = request.Execute();
if ( !result )
{
wxLogError("Request failed: %s", result.error);
}
else
{
// Do something with the response data, e.g. show it in a text control:
text->SetValue(request.GetResponse().AsString());
}
wxWebRequestSync::Execute
Result Execute() const
Synchronously execute the request.
wxWebSessionSync::CreateRequest
wxWebRequestSync CreateRequest(const wxString &url)
Create a new synchronous request for the specified URL.
wxWebSessionSync::GetDefault
static wxWebSessionSync & GetDefault()
Returns the default session.
wxLogError
void wxLogError(const char *formatString,...)
The functions to use for error messages, i.e.

To handle authentication with this class the username and password must be specified in the URL itself and wxWebAuthChallenge is not used with it.

Note
  Any reserved characters (see RFC 3986) in the username or password must be percent encoded. wxURI::SetUserAndPassword() can be used to ensure that this is done correctly.
  macOS backend using NSURLSession doesn't handle encoded characters in the password (but does handle them in the username). Async wxWebSession must be used if you need to support them under this platform.

See also
  wxWebRequest

Since
  3.3.0

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

## Classes
struct | Result
| Result of a synchronous operation. More...

## Public Types
enum | State { State_Idle , State_Unauthorized , State_Active , State_Completed , State_Failed , State_Cancelled }
| Possible request states returned in the state field of Result. More...
enum | Storage { Storage_Memory , Storage_File , Storage_None }
| Possible storage types. More...

## Public Member Functions
| wxWebRequestSync ()
| 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...
Result | Execute () const
| Synchronously execute the request. More...
wxWebResponse | GetResponse () const
| Returns a response object after a successful request. More...
wxFileOffset | GetBytesReceived () const
| Returns the total number of bytes 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 wxWebRequestSync::State

Possible request states returned in the state field of Result.

Enumerator
State_Idle | This state is not used with synchronous requests.
State_Unauthorized | The request is unauthorized. Use an URL with the username and password to access this resource.
State_Active | This state is not used with synchronous requests.
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 | This state is not used with synchronous requests.

## ◆ Storage

enum wxWebRequestSync::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. This storage method is not useful for the synchronous requests as data is simply lost when it is used, however it is still supported just in case the received data is really not needed.

## Constructor & Destructor Documentation

## ◆ wxWebRequestSync()

wxWebRequestSync::wxWebRequestSync | ( |  | ) |

Default constructor creates an invalid object.

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

See also
  IsOk()

## Member Function Documentation

## ◆ DisablePeerVerify()

void wxWebRequestSync::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.

Please notice that this function currently has no effect under macOS.

See also
  MakeInsecure()

## ◆ Execute()

Result wxWebRequestSync::Execute | ( |  | ) | const

Synchronously execute the request.

This function blocks for potentially long time and so must not be used from the main thread.

## ◆ GetBytesReceived()

wxFileOffset wxWebRequestSync::GetBytesReceived | ( |  | ) | const

Returns the total number of bytes received from the server.

This value is available after calling Execute().

## ◆ GetNativeHandle()

wxWebRequestHandle wxWebRequestSync::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 executed successfully using Execute().

See also
  wxWebSession::GetNativeHandle()

## ◆ GetResponse()

wxWebResponse wxWebRequestSync::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`.

## ◆ IsOk()

bool wxWebRequestSync::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 wxWebRequestSync::IsPeerVerifyDisabled | ( |  | ) | const

Return true if SSL certificate verification has been disabled.

See also
  DisablePeerVerify(), GetSecurityFlags()

## ◆ MakeInsecure()

void wxWebRequestSync::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 notice that this function currently has no effect under macOS.

Since
  3.3.0

## ◆ SetData() [1/3]

void wxWebRequestSync::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 wxWebRequestSync::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 wxWebRequestSync::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 wxWebRequestSync::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 wxWebRequestSync::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 wxWebRequestSync::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.