Make a HTTP Client
In some cases, you may need to make multiple requests to the same server. In such cases, it is more efficient to create an HTTP client and reuse it for multiple requests. The HttpClient struct provides a way to create an HTTP client that can be reused for multiple requests.
The HTTP Client holds a connection pool to reuse the connections, so it is more efficient than creating a new connection for each request.
And the client also provides a way to set more complex options like enable_redirect, user_agent for us to control the behavior of the client. See: HttpClient.new for more details.
Create a HTTP client
nv,no_run
use std.net.http.client.{HttpClient, Request};
use std.net.http.OK;
fn main() throws {
let client = HttpClient.new(
max_redirect_count: 5,
user_agent: "navi-client",
);
let req = try Request.get("https://httpbin.org/get");
let res = try client.request(req);
if (res.status() != OK) {
try println("Failed to fetch repo", res.text());
return;
}
try println(res.text());
}In the above example:
- We create an HTTP client using the
HttpClient.newfunction. - We set the
max_redirect_countto5, anduser_agenttonavi-client.- The
max_redirect_countis the maximum number of redirects to follow. - The
user_agentis theUser-Agentheader to send with the request.
- The
- We create a
Requestobject using theRequest.getmethod and set the URL of the GitHub API. - Then we send the request using the
HttpClient.requestmethod.