HTTP is a protocol. It defines the way computers communicate with each other. There a lot of different protocols out there; HTTP/2 and HTTP is based on TCP/IP, which almost all computers use to connect to servers. TCP/IP specifies how to create a connection between a client and a specific server, and send raw bytes. HTTP(2) is a layer over this, which defines how a client should tell the server what resource it wants.
The API provided by base POSIX extends to only raw TCP/IP. Here's an example of what an application could send to a web server to request a web page (this is an HTTP/1 request, HTTP/2 is binary and encrypted, making it not human-readable)
GET /somepage HTTP/1.0
Host: example.com
However, it's kind of inconvenient to assemble these requests manually in your program, especially when you start doing things like sending parameters, encryption, etc. In this case, people should use some libraries on the machine. It's important that these are nonstandard. Probably one of the most common ones is libcurl
.
Here's a libcurl tutorial. To summarize:
You can compile your program with libcurl by providing some flags to the compiler and the linker. You can get these by running curl-config --cflags
and curl-config --libs
.
Initialize libcurl with curl_global_init(bitfield)
. The bitfield can have CURL_GLOBAL_WIN32
and CURL_GLOBAL_SSL
as its values. You probably need CURL_GLOBAL_SSL
since you want to use encryption.
libcurl has two interfaces: easy
and multi
. I am going to cover easy
.
Get an easy handle by calling curl_easy_init()
. This handle allows you to make requests.
Set options on the handle by using curl_easy_setopt(handle, option, value)
. handle
is the "easy handle" you obtained, option
is a constant - for example CURLOPT_URL
for setting the URL to request - and value
is the value you want to set it to. It's often a string.
Set a callback function with option
as CURLOPT_WRITEFUNCTION
. It should have the signature size_t(void *buffer, size_t size, size_t nmemb, void *userp)
. It's called when libcurl receives data from the server. Usually, it's called many times. nmemb
points out the size of the data in buffer
. It should return the count of bytes it successfully processed. Normally this is nmemb
.
Execute the request with curl_easy_perform(handle)
.
When you're done with every request you want to make, call curl_global_cleanup()
.