Web Requests With HTTP 18
Web Requests With HTTP 18
Introduction
SFML provides a simple HTTP client class which you can use to communicate
with HTTP servers. "Simple" means that it supports the most basic features of
HTTP: POST, GET and HEAD request types, accessing HTTP header fields,
and reading/writing the pages body.
If you need more advanced features, such as secured HTTP (HTTPS) for
example, you're better off using a true HTTP library, like libcurl or cpp-netlib.
For basic interaction between your program and an HTTP server, it should be
enough.
sf::Http
To communicate with an HTTP server you must use the sf::Http class.
#include <SFML/Network.hpp>
sf::Http http;
http.setHost( "http://www.some-server.org/");
// or
Note that setting the host doesn't trigger any connection. A temporary
connection is created for each request.
The only other function in sf::Http, sends requests. This is basically all that
the class does.
sf::Http::Request request;
1
sf::Http::Response response = http.sendRequest(request);
Requests
An HTTP request, represented by the sf::Http::Request class, contains the
following information:
request.setMethod(sf::Http::Request::Post);
request.setUri( "/page.html");
request.setBody( "para1=value1¶m2=value2");
Responses
If the sf::Http class could successfully connect to the host and send the
request, a response is sent back and returned to the user, encapsulated in an
2
instance of the sf::Http::Response class. Responses contain the following
members:
o A status code which precisely indicates how the server processed the
request (OK, redirected, not found, etc.)
o The HTTP version of the server
o The header: a set of fields with key and value
o The body of the response
sf::Http::Response response = http.sendRequest(request);
std ::cout << "HTTP version: " << response.getMajorHttpVersion() << "." <<
std::endl;
The status code can be used to check whether the request was successfully
processed or not: codes 2xx represent success, codes 3xx represent a
redirection, codes 4xx represent client errors, codes 5xx represent server
errors, and codes 10xx represent SFML specific errors which are not part of
the HTTP standard.
#include <SFML/Network.hpp>
#include <sstream>
3
// prepare the request
std::ostringstream stream;
request.setBody(stream.str());
if (response.getStatus() == sf::Http::Response::Ok)
else
4
And finally, here is a very simple example of what the PHP page on server
might look like.
<?php
$name = $_POST['name'];
$score = $_POST['score'];
else
?>