| | | | Browse by category |
How do I submit a GET/POST request to a CGI program?
Cause
Action
Submitting a CGI GET or POST query is made simple using ToolsPro's RWIHttpClient and RWIHttpAgent classes.
The first and most important step is to constuct a valid query string to send to the CGI program. Data is sent as key/value pairs, where the same key may be used multiple times. Keys are seperated from values with the '=' character, and key/value pairs are separated by the '&'. The ' ' is rewritten to a '+', and most other special characters are recoded as a '%' character followed by the hexadecimal value of the character.
To send a greeting Hello World, and a farewell Goodbye All as a POST request, we will send the following query string to the server.
greeting=Hello+World&farewell=Goodbye+AllThe CGI program will decode this as two key/value pairs. The first, greeting, with a value of Hello World, and the second, farewell, with the value Goodbye All.
Once we have encoded our data, we can GET/POST it.
Sending the data is simple. All that we need to do is create a RWIHttpClient (or RWIHttpAgent) instance, connect to the server, and then submit the request.
RWCString url; // path to CGI script on HTTP server RWCString data; // contains CGI query string described above// create client and connect RWIHttpClient client(RWIHttpVersion_1_0()); if(!client.connect('www.somewhere.org')) { cerr << 'connect failed...' << endl; exit(1); }
// create a POST request and append query string RWIHttpPost post(url); post.append(data);
/* Here is the code when using GET // create a GET request url.append('?' + data); RWIHttpGet get(url);
// send GET request RWIHttpReply reply = client.execute(get); */
// send POST request RWIHttpReply reply = client.execute(post); if(!reply.is2XX()) { cerr << 'bad reply code: ' << reply.code() << endl; }
RWNetBuf buffer; RWCString result; RWPortal portal = reply.portal();
// read reply from server while(buffer = portal.recv()) result += buffer; // and display it cout << result << endl;