Version 0 of http in Jacl

Updated 2009-10-26 20:35:14 by tpoindex

Jacl doesn't currently have the http package available as part of its built-in library, but you can use Jacl's java package to retrieve a URL.

Here is a small procedure to retrieve a text document via the class. If you want to retrieve binary data, you'll need to write a similar procedure that returns the raw bytes (instead of converting to strings, as this procedure does.)

package require java

# getUrl - returns a list of 4 elements
#          {contentType contentLength contentEncoding contentData}
#          NOTE: no error handling

proc getUrl {url} {
    set url [java::new $url]
    set urlconn [$url openConnection]

    set contentType [$urlconn getContentType]
    set contentLength [$urlconn getContentLength]
    set contentEncoding [$urlconn getContentEncoding]
    set contentInputStream [$urlconn getInputStream]

    set bufSize 65536
    set contentData ""
    set byteArray [java::new {byte[]} $bufSize]
    while { [set len [$contentInputStream read $byteArray]] >= 0 } {
        append contentData [[java::new {String byte[] int int} $byteArray 0 $len] toString]
    $contentInputStream close

    return [list $contentType $contentLength $contentEncoding $contentData]

# sample

set urldata [getUrl]
puts "content type: [lindex $urldata 0]"
puts "content length: [lindex $urldata 1]"
puts "content encoding: [lindex $urldata 2]"
puts "content data: [lindex $urldata 3]"