http.n
来自「tcl是工具命令语言」· N 代码 · 共 527 行 · 第 1/2 页
N
527 行
This command resets the HTTP transaction identified by \fItoken\fR, ifany. This sets the \fBstate(status)\fP value to \fIwhy\fP, which defaults to \fBreset\fR, and then calls the registered \fB\-command\fR callback..TP\fB::http::wait\fP \fItoken\fPThis is a convenience procedure that blocks and waits for thetransaction to complete. This only works in trusted code because ituses \fBvwait\fR. Also, it's not useful for the case where\fB::http::geturl\fP is called \fIwithout\fP the \fB-command\fP optionbecause in this case the \fB::http::geturl\fP call doesn't returnuntil the HTTP transaction is complete, and thus there's nothing towait for..TP\fB::http::data\fP \fItoken\fPThis is a convenience procedure that returns the \fBbody\fP element(i.e., the URL data) of the state array..TP\fB::http::error\fP \fItoken\fPThis is a convenience procedure that returns the \fBerror\fP elementof the state array..TP\fB::http::status\fP \fItoken\fPThis is a convenience procedure that returns the \fBstatus\fP element ofthe state array..TP\fB::http::code\fP \fItoken\fPThis is a convenience procedure that returns the \fBhttp\fP element of thestate array..TP\fB::http::ncode\fP \fItoken\fPThis is a convenience procedure that returns just the numeric returncode (200, 404, etc.) from the \fBhttp\fP element of the state array..TP\fB::http::size\fP \fItoken\fPThis is a convenience procedure that returns the \fBcurrentsize\fPelement of the state array, which represents the number of bytesreceived from the URL in the \fB::http::geturl\fP call..TP\fB::http::cleanup\fP \fItoken\fPThis procedure cleans up the state associated with the connectionidentified by \fItoken\fP. After this call, the procedureslike \fB::http::data\fP cannot be used to get informationabout the operation. It is \fIstrongly\fP recommended that you callthis function after you're done with a given HTTP request. Not doingso will result in memory not being freed, and if your app calls\fB::http::geturl\fP enough times, the memory leak could cause aperformance hit...or worse..TP\fB::http::register\fP \fIproto port command\fPThis procedure allows one to provide custom HTTP transport typessuch as HTTPS, by registering a prefix, the default port, and thecommand to execute to create the Tcl \fBchannel\fR. E.g.:.RS.CSpackage require httppackage require tlshttp::register https 443 ::tls::socketset token [http::geturl https://my.secure.site/].CE.RE.TP\fB::http::unregister\fP \fIproto\fPThis procedure unregisters a protocol handler that was previouslyregistered via \fBhttp::register\fR..SH "ERRORS"The \fBhttp::geturl\fP procedure will raise errors in the following cases:invalid command line options,an invalid URL,a URL on a non-existent host,or a URL at a bad port on an existing host.These errors mean that itcannot even start the network transaction.It will also raise an error if it gets an I/O error whilewriting out the HTTP request header.For synchronous \fB::http::geturl\fP calls (where \fB-command\fP isnot specified), it will raise an error if it gets an I/O error whilereading the HTTP reply headers or data. Because \fB::http::geturl\fPdoesn't return a token in these cases, it does all the requiredcleanup and there's no issue of your app having to call\fB::http::cleanup\fP..PPFor asynchronous \fB::http::geturl\fP calls, all of the above errorsituations apply, except that if there's any error while reading theHTTP reply headers or data, no exception is thrown. This is becauseafter writing the HTTP headers, \fB::http::geturl\fP returns, and therest of the HTTP transaction occurs in the background. The commandcallback can check if any error occurred during the read by calling\fB::http::status\fP to check the status and if its \fIerror\fP,calling \fB::http::error\fP to get the error message..PPAlternatively, if the main program flow reaches a point where it needsto know the result of the asynchronous HTTP request, it can call\fB::http::wait\fP and then check status and error, just as thecallback does..PPIn any case, you must still call\fBhttp::cleanup\fP to delete the state array when you're done..PPThere are other possible results of the HTTP transactiondetermined by examining the status from \fBhttp::status\fP.These are described below..TPokIf the HTTP transaction completes entirely, then status will be \fBok\fP.However, you should still check the \fBhttp::code\fP value to getthe HTTP status. The \fBhttp::ncode\fP procedure provides justthe numeric error (e.g., 200, 404 or 500) while the \fBhttp::code\fPprocedure returns a value like "HTTP 404 File not found"..TPeofIf the server closes the socket without replying, then no erroris raised, but the status of the transaction will be \fBeof\fP..TPerrorThe error message will also be stored in the \fBerror\fP statusarray element, accessible via \fB::http::error\fP..PPAnother error possibility is that \fBhttp::geturl\fP is unable towrite all the post query data to the server before the serverresponds and closes the socket.The error message is saved in the \fBposterror\fP status arrayelement and then \fBhttp::geturl\fP attempts to complete thetransaction.If it can read the server's responseit will end up with an \fBok\fP status, otherwise it will havean \fBeof\fP status..SH "STATE ARRAY"The \fB::http::geturl\fR procedure returns a \fItoken\fR that can be used toget to the state of the HTTP transaction in the form of a Tcl array.Use this construct to create an easy-to-use array variable:.CSupvar #0 $token state.CEOnce the data associated with the url is no longer needed, the statearray should be unset to free up storage.The \fBhttp::cleanup\fP procedure is provided for that purpose.The following elements ofthe array are supported:.RS.TP\fBbody\fRThe contents of the URL. This will be empty if the \fB\-channel\fRoption has been specified. This value is returned by the \fB::http::data\fP command..TP\fBcharset\fRThe value of the charset attribute from the \fBContent-Type\fR meta-datavalue. If none was specified, this defaults to the RFC standard\fBiso8859-1\fR, or the value of \fB$::http::defaultCharset\fR. Incomingtext data will be automatically converted from this charset to utf-8..TP\fBcoding\fRA copy of the \fBContent-Encoding\fR meta-data value..TP\fBcurrentsize\fRThe current number of bytes fetched from the URL.This value is returned by the \fB::http::size\fP command..TP\fBerror\fRIf defined, this is the error string seen when the HTTP transactionwas aborted..TP\fBhttp\fRThe HTTP status reply from the server. This valueis returned by the \fB::http::code\fP command. The format of this value is:.RS.CS\fIHTTP/1.0 code string\fP.CEThe \fIcode\fR is a three-digit number defined in the HTTP standard.A code of 200 is OK. Codes beginning with 4 or 5 indicate errors.Codes beginning with 3 are redirection errors. In this case the\fBLocation\fR meta-data specifies a new URL that contains therequested information..RE.TP\fBmeta\fRThe HTTP protocol returns meta-data that describes the URL contents.The \fBmeta\fR element of the state array is a list of the keys andvalues of the meta-data. This is in a format useful for initializingan array that just contains the meta-data:.RS.CSarray set meta $state(meta).CESome of the meta-data keys are listed below, but the HTTP standard definesmore, and servers are free to add their own..TP\fBContent-Type\fRThe type of the URL contents. Examples include \fBtext/html\fR,\fBimage/gif,\fR \fBapplication/postscript\fR and\fBapplication/x-tcl\fR..TP\fBContent-Length\fRThe advertised size of the contents. The actual size obtained by\fB::http::geturl\fR is available as \fBstate(size)\fR..TP\fBLocation\fRAn alternate URL that contains the requested data..RE.TP\fBposterror\fRThe error, if any, that occurred while writingthe post query data to the server..TP\fBstatus\fREither \fBok\fR, for successful completion, \fBreset\fR foruser-reset, \fBtimeout\fP if a timeout occurred before the transactioncould complete, or \fBerror\fR for an error condition. During thetransaction this value is the empty string..TP\fBtotalsize\fRA copy of the \fBContent-Length\fR meta-data value..TP\fBtype\fRA copy of the \fBContent-Type\fR meta-data value..TP\fBurl\fRThe requested URL..RE.SH EXAMPLE.DS# Copy a URL to a file and print meta-dataproc ::http::copy { url file {chunk 4096} } { set out [open $file w] set token [geturl $url -channel $out -progress ::http::Progress \\ -blocksize $chunk] close $out # This ends the line started by http::Progress puts stderr "" upvar #0 $token state set max 0 foreach {name value} $state(meta) { if {[string length $name] > $max} { set max [string length $name] } if {[regexp -nocase ^location$ $name]} { # Handle URL redirects puts stderr "Location:$value" return [copy [string trim $value] $file $chunk] } } incr max foreach {name value} $state(meta) { puts [format "%-*s %s" $max $name: $value] } return $token}proc ::http::Progress {args} { puts -nonewline stderr . ; flush stderr}.DE.SH "SEE ALSO"safe(n), socket(n), safesock(n).SH KEYWORDSsecurity policy, socket
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?