19

我希望使用OCaml访问 Yahoo Finance API。从本质上讲,它只是一堆从雅虎财经获取报价的 HTTP 请求。

我应该使用哪个模块?

我希望有异步 HTTP 请求。

4

2 回答 2

23

有使用lwt的可能性:

  • ocsigen有一个相当完整但有点复杂的实现
  • cohttp有点简单,但缺少一些有用的部分

使用opam安装:

$ opam install ocsigenserver cohttp

例如在顶层:

try Topdirs.dir_directory (Sys.getenv "OCAML_TOPLEVEL_PATH") with _ -> ();;
#use "topfind";;
#thread;;
#require "ocsigenserver";;
open Lwt

(* a simple function to access the content of the response *)
let content = function
  | { Ocsigen_http_frame.frame_content = Some v } ->
      Ocsigen_stream.string_of_stream 100000 (Ocsigen_stream.get v)
  | _ -> return ""

(* launch both requests in parallel *)
let t = Lwt_list.map_p Ocsigen_http_client.get_url
  [ "http://ocsigen.org/";
    "http://stackoverflow.com/" ]

(* maps the result through the content function *)
let t2 = t >>= Lwt_list.map_p content

(* launch the event loop *)
let result = Lwt_main.run t2

并使用 cohttp:

try Topdirs.dir_directory (Sys.getenv "OCAML_TOPLEVEL_PATH") with _ -> ();;
#use "topfind";;
#require "cohttp.lwt";;
open Lwt

(* a simple function to access the content of the response *)
let content = function
  | Some (_, body) -> Cohttp_lwt_unix.Body.string_of_body body
  | _ -> return ""

(* launch both requests in parallel *)
let t = Lwt_list.map_p Cohttp_lwt_unix.Client.get
  (List.map Uri.of_string
     [ "http://example.org/";
       "http://example2.org/" ])

(* maps the result through the content function *)
let t2 = t >>= Lwt_list.map_p content

(* launch the event loop *)
let v = Lwt_main.run t2

请注意,还可以使用 jane street 异步库的 cohttp 实现

于 2013-01-03T10:08:25.707 回答
3

仅作记录,还有带有 curl 多 API 支持的 ocurl

于 2013-01-09T13:49:38.547 回答