HTTP 获取请求 tcl

HTTP get request tcl

我在 tcl 8.6 中工作,我正在尝试向 google 发送获取请求。 这是我使用的以下代码:

我的问题是如何使用 tcl 向 google 发出获取请求?

package require http
::http::config -useragent "Mozilla/5.0"

set url http://www.google.com

set http [::http::geturl $url]
set html [::http::data $http]

return $html

您可以将此包装器用于 http::geturl:

package require uri
proc geturl_followRedirects {url args} {
    array set URI [::uri::split $url]
    for {set i 0} {$i < 5} {incr i} {
        set token [::http::geturl $url {*}$args]
        if {![string match {30[1237]} [::http::ncode $token]]} {return $token}
        array set meta [string tolower [set ${token}(meta)]]
        if {![info exist meta(location)]} {
            return $token
        }
        array set uri [::uri::split $meta(location)]
        unset meta
        if {$uri(host) eq {}} {set uri(host) $URI(host)}
        # problem w/ relative versus absolute paths
        set url [::uri::join {*}[array get uri]]
    }
}

该命令归功于 Donal Fellows 和 Keith Vetter,original。我对其进行了一些更新以利用 Tcl 8.6。它还最多检查 5 次而不是无限期地检查。我还采纳了 Paul Walton 的建议。

命令 returns 一个 http 令牌就像 http::geturl 一样,并采用与该命令相同的参数。

ivan73 指出此代码具有重定向 URL 将被大小写转换破坏的限制。可以说 url 很少使用大写字母,但这仍然是一个限制。我想不是

        array set meta [string tolower [set ${token}(meta)]]
        if {![info exist meta(location)]} {
            return $token
        }
        array set uri [::uri::split $meta(location)]
        unset meta

有人会用

        set location [lmap {k v} [set ${token}(meta)] {
            if {[string match -nocase location $k]} {set v} continue
        }]
        if {$location eq {}} {
            return $token
        }
        array set uri [::uri::split $location]

对于保留元结构的值(和键)的不区分大小写的匹配。