factor/contrib/http-client.factor

71 lines
2.2 KiB
Factor
Raw Normal View History

! Copyright (C) 2005 Slava Pestov.
2006-09-06 04:25:43 -04:00
! See http://factorcode.org/license.txt for BSD license.
2006-09-13 18:24:40 -04:00
REQUIRES: contrib/http ;
2006-09-06 04:25:43 -04:00
IN: http-client
2005-11-29 23:49:59 -05:00
USING: errors hashtables http kernel math namespaces parser
sequences io strings ;
: parse-host ( url -- host port )
#! Extract the host name and port number from an HTTP URL.
2005-09-24 15:21:17 -04:00
":" split1 [ string>number ] [ 80 ] if* ;
: parse-url ( url -- host resource )
2005-05-18 16:26:22 -04:00
"http://" ?head [
"URL must begin with http://" throw
] unless
2005-09-24 15:21:17 -04:00
"/" split1 [ "/" swap append ] [ "/" ] if* ;
: parse-response ( line -- code )
2005-05-18 16:26:22 -04:00
"HTTP/" ?head [ " " split1 nip ] when
" " split1 drop string>number ;
: read-response ( -- code header )
2006-01-17 10:47:15 -05:00
#! After sending a GET or POST we read a response line and
#! header.
flush readln parse-response read-header ;
: crlf "\r\n" write ;
: http-request ( host resource method -- )
write " " write write " HTTP/1.0" write crlf
"Host: " write write crlf ;
: get-request ( host resource -- )
"GET" http-request crlf ;
DEFER: http-get
: do-redirect ( code headers string -- code headers string )
#! Should this support Location: headers that are
#! relative URLs?
pick 302 = [
drop "Location" swap hash nip http-get
] when ;
2006-08-04 00:24:08 -04:00
: http-get ( url -- code headers string )
#! Opens a stream for reading from an HTTP URL.
parse-url over parse-host <client> [
get-request read-response stdio get contents
] with-stream do-redirect ;
: download ( url file -- )
#! Downloads the contents of a URL to a file.
2006-08-04 00:24:08 -04:00
>r http-get 2nip r> <file-writer> [ write ] with-stream ;
: post-request ( content-type content host resource -- )
#! Note: It is up to the caller to url encode the content if
#! it is required according to the content-type.
"POST" http-request [
"Content-Length: " write length number>string write crlf
"Content-Type: " write url-encode write crlf
crlf
] keep write ;
: http-post ( content-type content url -- code headers string )
#! Make a POST request. The content is URL encoded for you.
parse-url over parse-host <client> [
2006-08-04 00:24:08 -04:00
post-request flush read-response stdio get contents
] with-stream ;
2006-09-13 18:24:40 -04:00
PROVIDE: contrib/http-client ;