如何使用 OCaml Url 和 Cohttp

Tho*_*mas 2 api url json ocaml http

我正在尝试使用 OCaml 的 Url 和 Cohttp 模块来访问 API 并检索 JSON 数据。我不想以异步方式执行此操作。我没有网络/网络编程经验,所有模块文档都只是提供类型和方法的签名(对我没有太大帮助,因为我不知道它们是做什么的)。我正在尝试访问 bitstamp API 并检索比特币的出价。到目前为止我只知道如何声明一个URI

    let bitstamp_uri = Uri.of_string "http://www.bitstamp.net/api/ticker/";;
Run Code Online (Sandbox Code Playgroud)

但我现在知道如何调用 uri 来检索 json 数据。我如何使用现有的库来实现这一目标?我已经知道如何将 json 数据解析为我需要的类型。

Ash*_*wal 5

Cohttp 要求您使用 Lwt 或 Async,因此您必须学习这些库之一。幸运的是,检索 JSON 文本并解析它正是新的 Real World OCaml 书中的示例之一,您可以在此处免费在线阅读。第 18 章介绍 Async 和 Cohttp,第 15 章介绍 JSON 解析。

现在,真正回答你的问题:

$ utop
utop # #require "lwt.syntax";;
utop # #require "core";;
utop # open Core.Std;;
utop # #require "cohttp.lwt";;
utop # #require "uri";;

utop # let get_uri uri : string Or_error.t Lwt.t =
  let open Lwt in
  match_lwt Cohttp_lwt_unix.Client.get uri with
  | None ->
    let msg = sprintf "%s: no reply" (Uri.to_string uri) in
    return (Or_error.error_string msg)
  | Some (_, body) -> (
      lwt body = Cohttp_lwt_body.string_of_body body in
      return (Ok body)
    );;

utop # let bitstamp_uri = Uri.of_string "http://www.bitstamp.net/api/ticker/";;

utop # get_uri bitstamp_uri;;
- : string Or_error.t =
Core_kernel.Result.Ok
"{\"high\": \"755.00\", \"last\": \"675.20\", \"timestamp\": \"1384841189\", \"bid\": \"675.10\", \"volume\": \"72858.24608402\", \"low\": \"471.26\", \"ask\": \"675.20\"}" 
Run Code Online (Sandbox Code Playgroud)

在本例中我使用了 Core 和 Lwt。RWO 书使用 Async。如果你想完全避免异步编程的复杂性,那么你不能使用Cohttp。