Skip to content
Search

WxHTTP

lastmod 2014-09-05created 2014-09-045 edits

Sample example

A simple example of fetching data over the HTTP protocol is shown below.

#include <wx/wx.h>
#include <wx/string.h>
#include <wx/stream.h>
#include <wx/protocol/http.h>

#define HEADER_CONTENT_TYPE "Content-type"
#define DATA_CONTENT_TYPE "text/html; charset=utf-8"
#define REQUEST_TIMEOUT 10
#define CONNECT_RETRY 5

bool requestHttpBody(const wxString & host, const short port, const wxString & path, wxOutputStream & output)
{
    wxApp::IsMainLoopRunning();
    wxSocketBase::Initialize();

    wxHTTP http;
    http.SetHeader(wxT(HEADER_CONTENT_TYPE), wxT(DATA_CONTENT_TYPE));
    http.SetTimeout(REQUEST_TIMEOUT);

    for (int count = 0; count < CONNECT_RETRY; count++) {
        if (http.Connect(host, port) == true) {
            break;
        }
        // wxSleep(5);
    }

    bool result = false;

    if (http.GetError() == wxPROTO_NOERR) {
        wxInputStream * input = http.GetInputStream(path);
        input->Read(output);
        wxDELETE(input);
    } else {
        // Unable to connect!
    }

    http.Close();
    return result;
}

Custom Thread Access

If you want to access it from a new thread rather than the main thread, you must initialize in the main thread as shown below.

wxSocketBase::Initialize()

After that, the wxHTTP object can be used from a custom thread.

Favorite site