wxWidgets/samples/webrequest/webrequest.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

505 lines
18 KiB
C++
Raw Normal View History

2018-10-15 16:28:07 -04:00
/////////////////////////////////////////////////////////////////////////////
// Name: samples/webrequest.cpp
// Purpose: wxWebRequest Sample
// Author: Tobias Taschner
// Created: 2018-10-15
// Copyright: (c) 2018 wxWidgets development team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
2018-10-18 17:19:17 -04:00
#include "wx/notebook.h"
#include "wx/artprov.h"
#include "wx/creddlg.h"
2018-10-18 17:19:17 -04:00
#include "wx/webrequest.h"
#include "wx/filedlg.h"
2018-11-06 16:00:44 -05:00
#include "wx/image.h"
2018-10-15 16:28:07 -04:00
#ifndef wxHAS_IMAGES_IN_RESOURCES
#include "../sample.xpm"
#endif
2021-03-18 15:49:57 -04:00
#if !wxUSE_WEBREQUEST
#error "wxUSE_WEBREQUEST must be 1 for this sample."
#endif
2018-10-15 16:28:07 -04:00
class WebRequestFrame : public wxFrame
{
public:
2018-10-21 17:03:01 -04:00
enum Pages
{
Page_Image,
Page_Text,
Page_Download,
Page_Advanced
};
2018-10-15 16:28:07 -04:00
WebRequestFrame(const wxString& title):
wxFrame(NULL, wxID_ANY, title)
{
// set the frame icon
SetIcon(wxICON(sample));
Bind(wxEVT_CLOSE_WINDOW, &WebRequestFrame::OnClose, this);
2018-10-15 16:28:07 -04:00
// Prepare UI controls
wxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);
2018-10-21 17:03:01 -04:00
mainSizer->Add(new wxStaticText(this, wxID_ANY, "Request URL:"),
2018-10-15 16:28:07 -04:00
wxSizerFlags().Border());
2018-10-21 17:03:01 -04:00
m_urlTextCtrl = new wxTextCtrl(this, wxID_ANY,
"https://www.wxwidgets.org/downloads/logos/blocks.png",
wxDefaultPosition, wxDefaultSize,
wxTE_PROCESS_ENTER);
2018-10-21 17:03:01 -04:00
mainSizer->Add(m_urlTextCtrl,
2018-10-15 16:28:07 -04:00
wxSizerFlags().Expand().Border(wxLEFT | wxRIGHT));
m_urlTextCtrl->Bind(wxEVT_TEXT_ENTER, &WebRequestFrame::OnStartButton, this);
2018-10-15 16:28:07 -04:00
2018-10-21 17:03:01 -04:00
m_notebook = new wxNotebook(this, wxID_ANY);
m_notebook->Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, &WebRequestFrame::OnNotebookPageChanged, this);
2018-10-15 16:28:07 -04:00
2018-10-21 17:03:01 -04:00
// Image page
wxPanel* imagePanel = new wxPanel(m_notebook);
wxSizer* imageSizer = new wxBoxSizer(wxVERTICAL);
m_imageStaticBitmap = new wxStaticBitmap(imagePanel,
2018-10-15 16:28:07 -04:00
wxID_ANY, wxArtProvider::GetBitmap(wxART_MISSING_IMAGE));
2018-10-21 17:03:01 -04:00
imageSizer->Add(m_imageStaticBitmap, wxSizerFlags(1).Expand());
2018-10-15 16:28:07 -04:00
2018-10-21 17:03:01 -04:00
imagePanel->SetSizer(imageSizer);
m_notebook->AddPage(imagePanel, "Image", true);
2018-10-15 16:28:07 -04:00
2018-10-21 17:03:01 -04:00
// Text page
wxPanel* textPanel = new wxPanel(m_notebook);
wxSizer* textSizer = new wxBoxSizer(wxVERTICAL);
2018-10-15 16:28:07 -04:00
2018-10-21 17:03:01 -04:00
m_postCheckBox = new wxCheckBox(textPanel, wxID_ANY, "Post request body");
textSizer->Add(m_postCheckBox, wxSizerFlags().Border());
m_postCheckBox->Bind(wxEVT_CHECKBOX, &WebRequestFrame::OnPostCheckBox, this);
2018-10-15 16:28:07 -04:00
m_postRequestTextCtrl = new wxTextCtrl(textPanel, wxID_ANY,
"app=WebRequestSample&version=1",
wxDefaultPosition, wxSize(-1, FromDIP(60)), wxTE_MULTILINE);
2018-10-21 17:03:01 -04:00
textSizer->Add(m_postRequestTextCtrl,
wxSizerFlags().Expand().Border(wxLEFT | wxRIGHT));
2018-10-15 16:28:07 -04:00
2018-10-21 17:03:01 -04:00
textSizer->Add(new wxStaticText(textPanel, wxID_ANY, "Request body content type:"),
wxSizerFlags().Border());
m_postContentTypeTextCtrl = new wxTextCtrl(textPanel, wxID_ANY,
"application/x-www-form-urlencoded");
2018-10-21 17:03:01 -04:00
textSizer->Add(m_postContentTypeTextCtrl,
wxSizerFlags().Expand().Border(wxLEFT | wxRIGHT));
2018-10-15 16:28:07 -04:00
2018-10-21 17:03:01 -04:00
textSizer->Add(new wxStaticText(textPanel, wxID_ANY, "Response body:"),
2018-10-15 16:28:07 -04:00
wxSizerFlags().Border());
2018-10-21 17:03:01 -04:00
m_textResponseTextCtrl = new wxTextCtrl(textPanel, wxID_ANY, "",
2018-10-15 16:28:07 -04:00
wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY);
2018-10-21 17:03:01 -04:00
m_textResponseTextCtrl->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));
textSizer->Add(m_textResponseTextCtrl,
2018-10-15 16:28:07 -04:00
wxSizerFlags(1).Expand().Border(wxLEFT | wxRIGHT | wxBOTTOM));
2018-10-21 17:03:01 -04:00
textPanel->SetSizer(textSizer);
m_notebook->AddPage(textPanel, "Text");
// Download page
wxPanel* downloadPanel = new wxPanel(m_notebook);
wxSizer* downloadSizer = new wxBoxSizer(wxVERTICAL);
wxStaticText* downloadHeader = new wxStaticText(downloadPanel, wxID_ANY,
"The URL will be downloaded to a file.\n"
"Progress will be shown and you will be asked, where\n"
"to save the file when the download completed.");
downloadSizer->Add(downloadHeader, wxSizerFlags().Expand().Border());
downloadSizer->AddStretchSpacer();
m_downloadGauge = new wxGauge(downloadPanel, wxID_ANY, 100);
downloadSizer->Add(m_downloadGauge, wxSizerFlags().Expand().Border());
m_downloadStaticText = new wxStaticText(downloadPanel, wxID_ANY, "");
downloadSizer->Add(m_downloadStaticText, wxSizerFlags().Expand().Border());
downloadSizer->AddStretchSpacer();
downloadPanel->SetSizer(downloadSizer);
2018-10-21 17:03:01 -04:00
m_notebook->AddPage(downloadPanel, "Download");
// Advanced page
wxPanel* advancedPanel = new wxPanel(m_notebook);
wxSizer* advSizer = new wxBoxSizer(wxVERTICAL);
wxStaticText* advHeader = new wxStaticText(advancedPanel, wxID_ANY,
"As an example of processing data while\n"
"it's being received from the server, every\n"
"zero byte in the response will be counted below.");
advSizer->Add(advHeader, wxSizerFlags().Expand().Border());
advSizer->AddStretchSpacer();
m_advCountStaticText = new wxStaticText(advancedPanel, wxID_ANY, "0",
wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE_HORIZONTAL | wxST_NO_AUTORESIZE);
m_advCountStaticText->SetFont(m_advCountStaticText->GetFont()
.MakeBold().MakeLarger().MakeLarger());
advSizer->Add(m_advCountStaticText, wxSizerFlags().Expand().Border());
advSizer->AddStretchSpacer();
advancedPanel->SetSizer(advSizer);
2018-10-21 17:03:01 -04:00
m_notebook->AddPage(advancedPanel, "Advanced");
mainSizer->Add(m_notebook, wxSizerFlags(1).Expand().Border());
2018-10-31 17:49:34 -04:00
wxStdDialogButtonSizer* btnSizer = new wxStdDialogButtonSizer();
m_cancelButton = new wxButton(this, wxID_CANCEL, "Cancel");
m_cancelButton->Bind(wxEVT_BUTTON, &WebRequestFrame::OnCancelButton, this);
m_cancelButton->Disable();
btnSizer->AddButton(m_cancelButton);
m_startButton = new wxButton(this, wxID_OK, "&Start Request");
2018-10-21 17:03:01 -04:00
m_startButton->Bind(wxEVT_BUTTON, &WebRequestFrame::OnStartButton, this);
2018-10-31 17:49:34 -04:00
btnSizer->AddButton(m_startButton);
btnSizer->Realize();
mainSizer->Add(btnSizer, wxSizerFlags().Expand().Border());
2018-10-21 17:03:01 -04:00
wxCommandEvent evt;
OnPostCheckBox(evt);
2018-10-15 16:28:07 -04:00
SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));
SetSizer(mainSizer);
SetSize(FromDIP(wxSize(540, 500)));
2018-10-15 16:28:07 -04:00
CreateStatusBar();
wxLogStatus(this, "%s", wxWebSession::GetDefault().GetLibraryVersionInfo().ToString());
m_downloadProgressTimer.Bind(wxEVT_TIMER,
&WebRequestFrame::OnProgressTimer, this);
2018-10-15 16:28:07 -04:00
}
virtual ~WebRequestFrame()
{
// We have to block until the web request completes, but we need to
// process events while doing it.
Hide();
while ( m_currentRequest.IsOk() )
{
wxYield();
}
}
2018-10-21 17:03:01 -04:00
void OnStartButton(wxCommandEvent& WXUNUSED(evt))
2018-10-15 16:28:07 -04:00
{
wxLogStatus(this, "Started request...");
2018-10-18 17:19:17 -04:00
// Create request for the specified URL from the default session
m_currentRequest = wxWebSession::GetDefault().CreateRequest(this,
m_urlTextCtrl->GetValue());
2018-10-18 17:19:17 -04:00
// Bind event for state change
Bind(wxEVT_WEBREQUEST_STATE, &WebRequestFrame::OnWebRequestState, this);
2018-10-18 17:19:17 -04:00
2018-10-21 17:03:01 -04:00
// Prepare request based on selected action
switch (m_notebook->GetSelection())
{
2018-10-31 17:49:34 -04:00
case Page_Image:
// Reset static bitmap image
m_imageStaticBitmap->SetBitmap(wxArtProvider::GetBitmap(wxART_MISSING_IMAGE));
break;
case Page_Text:
// Reset response text control
m_textResponseTextCtrl->Clear();
2018-10-31 17:49:34 -04:00
// Set postdata if checked
if ( m_postCheckBox->IsChecked() )
{
m_currentRequest.SetData(m_postRequestTextCtrl->GetValue(),
2018-10-31 17:49:34 -04:00
m_postContentTypeTextCtrl->GetValue());
}
break;
case Page_Download:
m_currentRequest.SetStorage(wxWebRequest::Storage_File);
2018-10-31 17:49:34 -04:00
m_downloadGauge->SetValue(0);
m_downloadGauge->Pulse();
m_downloadStaticText->SetLabel("");
m_downloadProgressTimer.Start(500);
SetStatusText("");
2018-10-31 17:49:34 -04:00
break;
case Page_Advanced:
m_currentRequest.SetStorage(wxWebRequest::Storage_None);
Bind(wxEVT_WEBREQUEST_DATA, &WebRequestFrame::OnRequestData, this);
wxLogStatus(this, "Counting...");
2018-10-31 17:49:34 -04:00
m_advCount = 0;
m_advCountStaticText->SetLabel("0");
break;
2018-10-21 17:03:01 -04:00
}
m_startButton->Disable();
// Start the request (events will be sent on success or failure)
m_currentRequest.Start();
2018-10-18 17:19:17 -04:00
}
2018-10-31 17:49:34 -04:00
void OnCancelButton(wxCommandEvent& WXUNUSED(evt))
{
if ( m_currentRequest.IsOk() )
m_currentRequest.Cancel();
2018-10-31 17:49:34 -04:00
}
void OnWebRequestState(wxWebRequestEvent& evt)
2018-10-21 17:03:01 -04:00
{
m_startButton->Enable(evt.GetState() != wxWebRequest::State_Active);
2018-10-31 17:49:34 -04:00
m_cancelButton->Enable(evt.GetState() == wxWebRequest::State_Active);
bool stillActive = false;
2018-10-18 17:19:17 -04:00
switch (evt.GetState())
{
case wxWebRequest::State_Completed:
switch (m_notebook->GetSelection())
{
2018-10-31 17:49:34 -04:00
case Page_Image:
{
wxImage img(*evt.GetResponse().GetStream());
2018-10-31 17:49:34 -04:00
m_imageStaticBitmap->SetBitmap(img);
m_notebook->GetPage(Page_Image)->Layout();
wxLogStatus(this, "Loaded %lld bytes image data", evt.GetResponse().GetContentLength());
2018-10-31 17:49:34 -04:00
break;
}
2018-10-31 17:49:34 -04:00
case Page_Text:
m_textResponseTextCtrl->SetValue(evt.GetResponse().AsString());
wxLogStatus(this, "Loaded %lld bytes text data (Status: %d %s)",
evt.GetResponse().GetContentLength(),
evt.GetResponse().GetStatus(),
evt.GetResponse().GetStatusText());
2018-10-31 17:49:34 -04:00
break;
case Page_Download:
{
m_downloadGauge->SetValue(100);
m_downloadStaticText->SetLabel("");
wxLogStatus(this, "Download completed");
2018-10-31 17:49:34 -04:00
// Ask the user where to save the file
wxFileDialog fileDlg(this, "Save download", "",
evt.GetResponse().GetSuggestedFileName(), "*.*",
2018-10-31 17:49:34 -04:00
wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
if ( fileDlg.ShowModal() == wxID_OK )
{
if ( !wxRenameFile(evt.GetDataFile(), fileDlg.GetPath()) )
2018-10-31 17:49:34 -04:00
wxLogError("Could not move file");
}
break;
}
case Page_Advanced:
UpdateAdvCount();
SetStatusText("");
2018-10-31 17:49:34 -04:00
break;
}
break;
case wxWebRequest::State_Failed:
wxLogError("Web Request failed: %s", evt.GetErrorDescription());
SetStatusText("");
break;
2018-10-31 17:49:34 -04:00
case wxWebRequest::State_Cancelled:
m_downloadGauge->SetValue(0);
m_downloadStaticText->SetLabel("");
wxLogStatus(this, "Cancelled");
2018-10-31 17:49:34 -04:00
break;
case wxWebRequest::State_Unauthorized:
{
wxWebAuthChallenge
auth = m_currentRequest.GetAuthChallenge();
if ( !auth.IsOk() )
{
wxLogStatus("Unexpectedly missing auth challenge");
break;
}
wxCredentialEntryDialog dialog
(
this,
wxString::Format
(
"Please enter credentials for accessing\n"
"%s",
evt.GetResponse().GetURL()
),
"wxWidgets web request sample",
m_credentials
);
if ( dialog.ShowModal() == wxID_OK )
{
m_credentials = dialog.GetCredentials();
auth.SetCredentials(m_credentials);
wxLogStatus("Trying to authenticate...");
stillActive = true;
}
}
break;
case wxWebRequest::State_Active:
stillActive = true;
break;
case wxWebRequest::State_Idle:
// Nothing special to do for this state.
break;
}
if ( !stillActive )
{
m_currentRequest = wxWebRequest();
m_downloadProgressTimer.Stop();
}
2018-10-21 17:03:01 -04:00
}
void OnRequestData(wxWebRequestEvent& evt)
{
// Count zero bytes in data buffer
const char* p = (const char*) evt.GetDataBuffer();
for ( size_t i = 0; i < evt.GetDataSize(); i++ )
{
if ( *p == 0 )
m_advCount++;
p++;
}
UpdateAdvCount();
// Make sure the new text is immediately visible.
m_advCountStaticText->Update();
}
void UpdateAdvCount()
{
m_advCountStaticText->SetLabel(wxString::Format("%lld", m_advCount));
}
void OnProgressTimer(wxTimerEvent& WXUNUSED(evt))
{
if ( !m_currentRequest.IsOk() || m_currentRequest.GetBytesExpectedToReceive() <= 0 )
return;
m_downloadGauge->SetValue((m_currentRequest.GetBytesReceived() * 100) /
m_currentRequest.GetBytesExpectedToReceive());
m_downloadStaticText->SetLabelText(wxString::Format("%lld/%lld",
m_currentRequest.GetBytesReceived(), m_currentRequest.GetBytesExpectedToReceive()));
}
2018-10-21 17:03:01 -04:00
void OnPostCheckBox(wxCommandEvent& WXUNUSED(evt))
{
m_postContentTypeTextCtrl->Enable(m_postCheckBox->IsChecked());
m_postRequestTextCtrl->Enable(m_postCheckBox->IsChecked());
wxColour textBg = wxSystemSettings::GetColour(
(m_postCheckBox->IsChecked()) ? wxSYS_COLOUR_WINDOW : wxSYS_COLOUR_BTNFACE);
m_postContentTypeTextCtrl->SetBackgroundColour(textBg);
m_postRequestTextCtrl->SetBackgroundColour(textBg);
2018-10-15 16:28:07 -04:00
}
2018-10-21 17:03:01 -04:00
void OnNotebookPageChanged(wxBookCtrlEvent& event)
2018-10-15 16:28:07 -04:00
{
2018-10-21 17:03:01 -04:00
wxString defaultURL;
switch (event.GetSelection())
{
case Page_Image:
defaultURL = "https://www.wxwidgets.org/downloads/logos/blocks.png";
break;
case Page_Text:
defaultURL = "https://httpbin.org/post";
2018-10-21 17:03:01 -04:00
break;
case Page_Download:
defaultURL = "https://github.com/wxWidgets/wxWidgets/releases/download/v3.1.1/wxWidgets-3.1.1.7z";
2018-10-21 17:03:01 -04:00
break;
case Page_Advanced:
defaultURL = "https://httpbin.org/bytes/100000";
2018-10-21 17:03:01 -04:00
break;
}
m_urlTextCtrl->SetValue(defaultURL);
2018-10-15 16:28:07 -04:00
}
void OnClose(wxCloseEvent& event)
{
if ( m_currentRequest.IsOk() )
{
if ( event.CanVeto() )
{
wxMessageDialog dialog
(
this,
"A web request is in progress, "
"closing the window will cancel it.",
"Please confirm",
wxYES_NO
);
dialog.SetYesNoLabels("Cancel and close", "Don't close");
if ( dialog.ShowModal() != wxID_YES )
{
event.Veto();
return;
}
}
m_currentRequest.Cancel();
}
event.Skip();
}
2018-10-15 16:28:07 -04:00
private:
2018-10-21 17:03:01 -04:00
wxNotebook* m_notebook;
wxTextCtrl* m_urlTextCtrl;
wxButton* m_startButton;
2018-10-31 17:49:34 -04:00
wxButton* m_cancelButton;
2018-10-21 17:03:01 -04:00
wxStaticBitmap* m_imageStaticBitmap;
wxWebRequest m_currentRequest;
2018-10-15 16:28:07 -04:00
2018-10-21 17:03:01 -04:00
wxCheckBox* m_postCheckBox;
2018-10-15 16:28:07 -04:00
wxTextCtrl* m_postContentTypeTextCtrl;
wxTextCtrl* m_postRequestTextCtrl;
2018-10-21 17:03:01 -04:00
wxTextCtrl* m_textResponseTextCtrl;
wxGauge* m_downloadGauge;
wxStaticText* m_downloadStaticText;
wxTimer m_downloadProgressTimer;
wxStaticText* m_advCountStaticText;
wxLongLong m_advCount;
// Normally it would be a bad idea to permanently store credentials like
// this, we should use wxSecretStore to load them as needed, but let's keep
// things simple in this example.
wxWebCredentials m_credentials;
2018-10-15 16:28:07 -04:00
};
class WebRequestApp : public wxApp
{
public:
virtual bool OnInit() wxOVERRIDE
{
if ( !wxApp::OnInit() )
2018-10-15 16:28:07 -04:00
return false;
2018-11-06 16:00:44 -05:00
wxInitAllImageHandlers();
2018-10-15 16:28:07 -04:00
// create the main application window
WebRequestFrame *frame = new WebRequestFrame("wxWebRequest Sample App");
frame->Show(true);
return true;
}
};
wxIMPLEMENT_APP(WebRequestApp);