# This gets the title of a web page by making an HTTP connection and parsing the result for a
tag.
subroutine(get_title_by_http_or_https(string hostname, string uri, bool https), (
# Connect to the HTTP server
int port = if (https) then 443 else 80;
if (matches_regular_expression(hostname, '^([^:]+):([0-9]+)$')) then (
hostname = $1;
port = $2;
# echo("Split hostname=" . hostname . "; port=" . port);
);
string socket = connect(hostname, port, https);
# echo("connected: " . socket);
# Send a GET request to get the specified URI
data d = "GET " . uri . " HTTP/1.1\r\nHost: " . hostname . "\r\n\r\n";
# data d = "GET /faq.html HTTP/1.1\r\nHost: " . hostname . "\r\n\r\n";
write_to_socket(socket, d, length(d));
# echo("wrote " . d);
# Read the result in the following loop
int read = 1;
int contentLength = -1;
string totalResponse;
string headers;
string body;
bool done = false;
bool inHeaders = true;
bool chunked = false;
int chunkLength;
string chunkedBody;
string chunk;
string title;
while (!done) (
# echo("Reading from socket");
read_from_socket(socket, d, 10000);
if (length(d) == 0) then
done = true;
# echo(">>> Read " . length(d) . " bytes from socket");
if (contains(d, "