Skip to content

Instantly share code, notes, and snippets.

@zbroyar
Created December 5, 2011 06:28
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save zbroyar/1432555 to your computer and use it in GitHub Desktop.
Save zbroyar/1432555 to your computer and use it in GitHub Desktop.
OCaml CURL GET, POST, PUT, DELETE examples
(* ocamlfind ocamlopt -o exmpl -package curl -linkpkg exmpl.ml *)
open Printf
let _ = Curl.global_init Curl.CURLINIT_GLOBALALL
(*
*************************************************************************
** Aux. functions
*************************************************************************
*)
let writer_callback a d =
Buffer.add_string a d;
String.length d
let init_conn url =
let r = Buffer.create 16384
and c = Curl.init () in
Curl.set_timeout c 1200;
Curl.set_sslverifypeer c false;
Curl.set_sslverifyhost c Curl.SSLVERIFYHOST_EXISTENCE;
Curl.set_writefunction c (writer_callback r);
Curl.set_tcpnodelay c true;
Curl.set_verbose c false;
Curl.set_post c false;
Curl.set_url c url; r,c
(*
*************************************************************************
** GET, POST, PUT, DELETE
*************************************************************************
*)
(* GET *)
let get url =
let r,c = init_conn url in
Curl.set_followlocation c true;
Curl.perform c;
let rc = Curl.get_responsecode c in
Curl.cleanup c;
rc, (Buffer.contents r)
(* POST *)
let post ?(content_type = "text/html") url data =
let r,c = init_conn url in
Curl.set_post c true;
Curl.set_httpheader c [ "Content-Type: " ^ content_type ];
Curl.set_postfields c data;
Curl.set_postfieldsize c (String.length data);
Curl.perform c;
let rc = Curl.get_responsecode c in
Curl.cleanup c;
rc, (Buffer.contents r)
(* PUT *)
let put ?(content_type = "text/html") url data =
let pos = ref 0
and len = String.length data in
let rf cnt =
let can_send = len - !pos in
let to_send = if can_send > cnt then cnt else can_send in
let r = String.sub data !pos to_send in
pos := !pos + to_send; r
and r,c = init_conn url in
Curl.set_put c true;
Curl.set_upload c true;
Curl.set_readfunction c rf;
Curl.set_httpheader c [ "Content-Type: " ^ content_type ];
Curl.perform c;
let rc = Curl.get_responsecode c in
Curl.cleanup c;
rc, (Buffer.contents r)
(* DELETE *)
let delete url =
let r,c = init_conn url in
Curl.set_customrequest c "DELETE";
Curl.set_followlocation c false;
Curl.perform c;
let rc = Curl.get_responsecode c in
Curl.cleanup c;
rc, (Buffer.contents r)
(*
*************************************************************************
** Check
*************************************************************************
*)
let _ =
let r,c = put "http://localhost/test" "test" in
printf "%d -> %s\n" r c
@cljoly
Copy link

cljoly commented Jun 20, 2015

You can find a repository on Gitlab

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment