【问题标题】:What is the best module for HttpRequest in OCamlOCaml 中 HttpRequest 的最佳模块是什么
【发布时间】:2013-01-03 06:34:41
【问题描述】:

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

我应该使用哪个模块?

我希望有异步 HTTP 请求。

【问题讨论】:

  • @BasileStarynkevitch 不是真的,我是一个全新的学习者,一无所知。 Ocamlnet 是最好的吗?
  • 不知道是不是最好的,但是很好。
  • @BasileStarynkevitch 是否提供async ability
  • 我最近使用 ocamlnet 来达到这个目的,但没有异步功能。

标签: ocaml ocaml-batteries


【解决方案1】:

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

【讨论】:

  • "+../toplevel" 在这里有点误导:这对于 OPAM 安装的编译器来说不是必需的,并且它不适用于系统编译器(您应该改用 try Topdirs.dir_directory (Sys.getenv "OCAML_TOPLEVEL_PATH") with _ -> ()) .
  • @Thomas 我认为您的建议非常好。而且我无法运行代码,但可以使用您的try Topdirs.dir_directory (Sys.getenv "OCAML_TOPLEVEL_PATH") with _ -> ()。你能修改他的其他代码吗?
  • @Thomas 我是新手,你能告诉我Some (_, body)是什么吗?
  • 这是一个与可选对匹配的模式。在这种情况下,该对的第一个元素被丢弃,第二个元素绑定到名称“body”。如果您想了解更多信息,请阅读“模式匹配”。
  • @JacksonTale 这是 Lwt.bind 的一些糖。见Lwt doc
【解决方案2】:

仅作记录,还有ocurl with curl multi API support

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    相关资源
    最近更新 更多