Module Webs.Http_client

HTTP clients.

See examples.

Clients

val default_max_redirection : int

default_max_redirection is the default maximal number of redirections when they are followed, see request.

type t

The type for HTTP clients.

val id : t -> string

id httpc identifies the underlying implementation of httpc.

val request : ?max_redirections:int -> t -> follow:bool -> Http.Request.t -> (Http.Response.t, string) Stdlib.result

request httpc ~follow request performs request request via httpc. To construct a request from an URL use Http.Request.of_url. Read more details about how request is interpreted by client connectors in the client connector conventions.

If follow is true and the request is GET or HEAD, HTTP responses are automatically redirected on 301, 302, 303, 305, 307 and 308. In this case the the original request is modified as follows:

In case there was a follow, the final requested URL can be found in the response in the x_follow_location header.

val get : t -> follow:bool -> url:Webs_url.t -> (string, string) Stdlib.result

get c ~follow ~url is the body of a GET request on url. For the semantics of follow see request.

Note. This is voluntarily kept bare bones (e.g. no headers can be specified). Anything more complex should use request.

val x_follow_location : Http.Headers.Name.t

x_follow_location is the final location that was requested when follow is true.

Examples

This fetches https://example.org with Webs_spawn_client and Http_client.get.

open Webs

let main () =
  let httpc = Webs_spawn_client.make () in
  let url = "https://example.org" in
  match Http_client.get httpc ~follow:true ~url with
  | Error e -> prerr_endline e; 1
  | Ok page -> print_endline page; 0

let () = if !Sys.interactive then () else exit (main ())

This shows how to use Http_client.request to implement Http_client.get.

open Webs
let ( let* ) = Result.bind

let get httpc ~follow ~url =
  let* request = Http.Request.of_url `GET ~url in
  let* response = Http_client.request httpc ~follow req in
  match Http.Response.status response with
  | 200 -> Http.Body.to_string (Http.Response.body response)
  | st -> Error (Format.asprintf "%a" Http.Status.pp st)

Client connectors

If you devise your own HTTP client it should provide constructor functions that return Http_client.t values directly. These values are constructed with make.

module type T = sig ... end

Client connector.

val make : (module T with type t = 'a) -> 'a -> t

make impl httpc packs an HTTP client implementation impl and its specific implementation httpc.