我希望使用 OCaml 来访问Yahoo Finance API。从本质上讲,它只是一堆HTTP请求来获取雅虎财经的报价。
我应该使用哪个模块?
我希望有异步HTTP请求。
答案 0 :(得分:23)
有使用lwt的可能性:
使用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实现也可用
答案 1 :(得分:3)