Http Client in Crystal
Here’s the translation of the Go HTTP client example to Crystal:
Our example demonstrates how to make HTTP requests using Crystal’s standard library. We’ll use it to issue simple HTTP requests.
To run the program, save it as http_client.cr
and use the crystal
command:
This example demonstrates several key points:
We use the
HTTP::Client
class from Crystal’s standard library to make HTTP requests.The
HTTP::Client.get
method is used to send a GET request to the specified URL. This method returns anHTTP::Client::Response
object.We can access the response status using
response.status_code
andresponse.status_message
.The response body is available through
response.body
. We useeach_line
to iterate over the lines of the body,first(5)
to limit it to the first 5 lines, and then print each line.Crystal automatically handles resource management, so we don’t need to explicitly close the response body.
This example showcases Crystal’s simplicity and expressiveness when working with HTTP requests. The language provides a straightforward way to perform common web-related tasks.