Course of Raku / Functional, concurrent, reactive, and web programming / Web programming / A simple HTTP client

A raw GET request

HTTP is a text protocol, so you can speak it directly over a socket. A GET request asks a server for a resource. It is a few lines of text: the request line, some headers, and a blank line to mark the end:

my $conn = IO::Socket::INET.new(:host('example.com'), :port(80));

$conn.print("GET / HTTP/1.0\r\nHost: example.com\r\n\r\n");

my $response = $conn.recv;
$conn.close;

say $response.lines.first; # HTTP/1.1 200 OK

The request GET / HTTP/1.0 asks for the root document /. The Host: header names the site, and the empty line — the second \r\n — tells the server the request is complete. The server then sends back a response whose first line is the status, such as HTTP/1.1 200 OK.

This example needs a working network connection.

Every line in the protocol ends with \r\n, and the blank line separating the headers from the body is essential — without it the server keeps waiting for more of the request. Writing HTTP by hand like this shows exactly what a request is. In practice you reach for a client module, which handles all these details for you, as the next topic shows.

Practice

Complete the quiz that covers the contents of this topic.

Course navigation

A simple HTTP client   |   Quiz — HTTP requests


💪 Or jump directly to the exercises in this section.