Is there any way to easily make a HTTP request with C++? Specifically, I want to download the contents of a page (an API) and check the contents to see if it contains a 1 or a 0. Is it also possible to download the contents into a string?
An HTTP client sends an HTTP request to a server in the form of a request message which includes following format: A Request-line. Zero or more header (General|Request|Entity) fields followed by CRLF. An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields.
C++ does not provide any way to do it directly. It would entirely depend on what platforms and libraries that you have. At worst case, you can use the boost::asio library to establish a TCP connection, send the HTTP headers (RFC 2616), and parse the responses directly.
HTTP works as a request-response protocol between a client and server. Example: A client (browser) sends an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.
I had the same problem. libcurl is really complete. There is a C++ wrapper curlpp that might interest you as you ask for a C++ library. neon is another interesting C library that also support WebDAV.
curlpp seems natural if you use C++. There are many examples provided in the source distribution. To get the content of an URL you do something like that (extracted from examples) :
// Edit : rewritten for cURLpp 0.7.3 // Note : namespace changed, was cURLpp in 0.7.2 ... #include <curlpp/cURLpp.hpp> #include <curlpp/Options.hpp> // RAII cleanup curlpp::Cleanup myCleanup; // Send request and get a result. // Here I use a shortcut to get it in a string stream ... std::ostringstream os; os << curlpp::options::Url(std::string("http://example.com")); string asAskedInQuestion = os.str();
See the examples
directory in curlpp source distribution, there is a lot of more complex cases, as well as a simple complete minimal one using curlpp.
my 2 cents ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With