2014年5月14日水曜日

[OCaml]Ocamlnetのhttp_clientでコンテンツを取得する

OCamlで簡単に使えるHTTPクライアントを探していたのだけど、
Ocamlnetライブラリのhttp_client.Convenienceモジュールを使うと、
とても簡単に、コンテンツを取得できた。

Ocamlnetのインストール

Ocamlnetはopamでインストールできる。
$ opam install ocamlnet
現時点のバージョンは3.7.3だった。

Http_client.Convenienceモジュール

Http_client.ConvenienceモジュールにはGETリクエストでコンテンツを取得する関数がある。
詳細はリファレンスマニュアルを参照。

val http_get : string -> string
  Does a "GET" request with the given URL and returns the message body
val http_get_message : string -> Http_client.http_call
  Does a "GET" request with the given URL and returns the message

サンプルコード

utopで試してみた。

utop[0]> #require "netclient";;
utop[1]> Http_client.Convenience.http_get "http://ほげほげ.com/";;
- : string =
"<html><body><h1>It works!</h1>
<p>This is the default web page for this server.</p>
<p>The web server software is running but no content has been added, yet.</p>
</body></html>
"
utop[2]> Http_client.Convenience.http_get_message "http://ほげほげ.com/";;
- : Http_client.http_call = <obj>
utop[4]> let c = Http_client.Convenience.http_get_message "http://ほげほげ.com/";;
val c : Http_client.http_call = <obj>
utop[6]> c#status;;
- : Http_client.status = `Successful
utop[7]> c#response_body;;
- : Netmime.mime_body = <obj>
utop[8]> c#response_body#value;;
- : string =
"<html><body><h1>It works!</h1>
<p>This is the default web page for this server.</p>
<p>The web server software is running but no content has been added, yet.</p>
</body></html>
"
utop[9]>

すごく簡単。

OCamlnetは、HTTPクライアント以外にも、FTP、POP、SMTP等、ネットワークに関連する様々なモジュールを提供している。
リファレンスは分かりやすく、結構便利だ。

参考


0 件のコメント:

コメントを投稿