Created
February 27, 2016 22:59
-
-
Save eatonphil/07f931899474cb096309 to your computer and use it in GitHub Desktop.
Example of HTTP GET request in SML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* | |
* Tested on Poly/ML. | |
* Usage: | |
* $ polyc getreq.sml | |
* $ ./a.out | |
*) | |
exception E of string | |
fun request domain path = | |
let | |
val req = "GET " ^ path ^ " HTTP/1.1\r\nHost: " ^ domain ^ "\r\n\r\n"; | |
val vec = Byte.stringToBytes(req); | |
val slice = Word8VectorSlice.slice(vec, 0, NONE); | |
val socket = INetSock.TCP.socket (); | |
val address = | |
let | |
val SOME entry = NetHostDB.getByName domain; | |
in | |
INetSock.toAddr (NetHostDB.addr entry, 80) | |
end; | |
val read = ref 0 | |
val rsp = ref "" | |
in | |
print (req); | |
Socket.connect (socket, address); | |
Socket.sendVec (socket, slice); | |
while (!read > 0 orelse !rsp = "") do | |
let | |
val vec = Socket.recvVec (socket, 1024); | |
val len = Word8Vector.length vec; | |
in | |
read := (if len < 1024 then 0 else 1); | |
rsp := !rsp ^ Byte.bytesToString (vec) | |
end; | |
print (!rsp); | |
Socket.close (socket) | |
end | |
fun main () = | |
request "api.ipify.org" "/" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment