ocaml - OCaml 中 HttpRequest 的最佳模块是什么

标签 ocaml ocaml-batteries

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

我应该使用哪个模块?

我希望有异步 HTTP 请求。

最佳答案

有可能使用 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 实现

    关于ocaml - OCaml 中 HttpRequest 的最佳模块是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14134116/

    相关文章:

    javascript - 如何使用算法 W 键入检查递归定义?

    performance - OCaml 异常的表现

    functional-programming - 模式匹配中的变量如何允许参数省略?

    ocaml - OCaml 中函数组合的尾递归版本

    makefile - 构建 OCaml 交叉编译器 - 配置部分

    Ocaml TRIE 实现

    ocaml - 通过 ocamlbuild 在 .mly 文件中使用电池