Very simple function for sending HTTP POST requests

If you have a cool piece of software to share, but you are not hosting it officially yet, please dump it in here. If you have code snippets that are useful, please donate!
Post Reply
ptDev
In need of some credit
In need of some credit
Posts: 7
Joined: Fri Nov 27, 2009 4:24 pm

Very simple function for sending HTTP POST requests

Post by ptDev » Sat Jul 10, 2010 8:31 am

After a couple of hours searching for a useful example, I finally found a chinese blog with a simple procedure (can't find the url now, sorry :oops:). From this example, I made a simple function that I can now use in any program whenever contacting a server through POST is needed.

It couldn't be any simpler. The reply is returned in the form of a wxString, and in case of failure, it is a wxEmptyString.

Code: Select all

#include <wx/protocol/http.h>
#include <wx/sstream.h>

const wxString wxHTTP_POST(const wxString& server, const wxString& page, const wxString& parameters)
{
   wxString reply = wxEmptyString;

   wxHTTP http;

   http.SetHeader("Content-type", "application/x-www-form-urlencoded");
   http.SetPostBuffer(parameters);

   http.Connect(server);
   wxInputStream *http_stream = http.GetInputStream("/"+page);

   if (http.GetError() == wxPROTO_NOERR)
   {
      wxStringOutputStream out_stream(&reply);
      http_stream->Read(out_stream);
   }
   else reply = wxEmptyString;

   wxDELETE(http_stream);
   http.Close();

   return reply;
}
Examples of use.
  • Login to a website:

    Code: Select all

    wxString server_reply = wxHTTP_POST("someserver.com","login.php","username=CoolUser&pass=My_PassWord");
    Search for "carrots" in google.com:

    Code: Select all

    wxString results = wxHTTP_POST("google.com","search","q=carrots");
Needless to say, the parameters need to be URL encoded, and you should handle the reply according to the format specified in the relevant site's API. It can be a simple confirmation string, an URL for redirection, or an entire web page.

I hope someone finds this useful. Happy hacking!

Regards.

maxinuruguay
I live to help wx-kind
I live to help wx-kind
Posts: 198
Joined: Sat Oct 28, 2006 3:36 am

Post by maxinuruguay » Sun Aug 15, 2010 8:47 am

This doesn't work on my machine 2.8.10 Windows 7 accessing a php script. If anyone gets this to work, I'd be interested in how you did it. In the meantime, upCase you are my hero! Your workaround works great.

http://forums.wxwidgets.org/viewtopic.p ... hlight=php

Post Reply