WxHTTP

From WxWiki
Jump to navigation Jump to search

wxHTTP Functions Missing from Docs

Functions found in src/common/http.cpp that you need to know about but that arn't documented in <wxref class="wxHTTP" method=""></wxref>.


wxHTTP::Abort

bool Abort(void)

Aborts an active transfer by closing the connection.


wxHTTP::Connect

bool Connect(wxSockAddress& addr, bool WXUNUSED(wait))

bool Connect(const wxString& host, unsigned short port)

These do not make an actual connection to a server but simple tell wxHTTP about the server you want to request pages from.


wxHTTP::SetPostBuffer

void SetPostBuffer(const wxString& post_buf)

Set the data to be posted to the server.


wxHTTP::GetContentType

wxString GetContentType()

Get the "Content-Type" header returned by the server.


wxHTTP::SetProxyMode

void SetProxyMode(bool on)

Set whether or not to use a proxy.


wxHTTP::ClearHeaders

void ClearHeaders()

Removes all headers.


wxHTTP::GetInputStream

wxInputStream *GetInputStream(const wxString& path)

Get a page from the server specified by the last call to Connect(...). Path is path to a resource on the server not a full URL. Note: You must call one of the Connect functions at least once before using this function or the result will be NULL.


Basic Usage

wxHTTP get;
get.SetHeader(_T("Content-type"), _T("text/html; charset=utf-8"));
get.Connect(_T("www.google.com")); // only the server, no pages here yet

wxApp::IsMainLoopRunning(); // should return true

// use _T("/") for index.html, index.php, default.asp, etc.
wxInputStream *httpStream = get.GetInputStream(_T("/intl/en/about.html"));

// wxLogVerbose( wxString(_T(" GetInputStream: ")) << get.GetResponse() << _T("-") << ((resStream)? _T("OK ") : _T("FAILURE ")) << get.GetError() );

if (http.GetError() == wxPROTO_NOERR)
{
    wxString res;
    while (!httpStream->Eof())
        res += httpStream->GetC();

    wxMessageBox(res);
// wxLogVerbose( wxString(_T(" returned document length: ")) << res.Length() );
}
else
{
    wxMessageBox(_T("Unable to connect!"));
}

delete httpStream;
get.Close();

Known issues

CPU used at 100%

Sometimes, when you try to use wxHTTP to get a file and the main loop is not running, your CPU usage comes to 100% and this overhead completely freeze your Windows (This issue doesn't appear under wxGTK). A small clue is in the wxApp documentation : <wxref class="wxApp" method="IsMainLoopRunning"></wxref> : "This can be useful to test whether the events can be dispatched. For example, if this function returns false, non-blocking sockets cannot be used because the events from them would never be processed." It looks like you can't use wxHTTP even in blocking mode until you are in main loop (at least on Windows platform).
So you should always test for being inside main loop before using wxHTTP (certainly other protocols too).