阿里巴巴, 做了B2B, 做了B2C。 有了钱, 有了人,就开始整合资源,想在这里分一杯羹
http://ningbo.koubei.com/cate
Showing posts with label blogger_build. Show all posts
Showing posts with label blogger_build. Show all posts
Wednesday, 20 June 2007
Tuesday, 22 May 2007
.bat&&http
I was wasting time on .bat and http these days.
i learn some stuff like:
start iexplore.exe url is used to open a browser with a given url
& in url is refer some variables in dynamic web, like jsp, asp, etc after ?
^ is used to escape the special char like &. we use \ in unix shell
we can do as in shell script using "" to quoto a statement, and in this quote we use %% to escape %
find out interface:
useing firefox to find out the infor of that form or post, then check out the post or ref with variable. there should be some encode, follow that and finish the whole url.
here is a easy .bat for opening several webs:
start iexplore.exe http://shaojianhua.bloggerspaces.com
start iexplore.exe http://dict.baidu.com
start iexplore.exe "https://www.google.com/accounts/ServiceLoginBoxAuth?continue=http%%3A%%2F%%2Fwww.blogger.com%%
2Floginz%%3Fd%%3D%%
252Fstart&service=blogger&nui=8&naui=8&fpui=2&uilel=3&skipvpage=true&rm=false&hl=zh_CN&alwf=true&roeu=https%%3A%%
2F%%2Fwww.blogger.com%%2Flogin.g&GA3T=H4Ef6yxjXys&Email=dustin.shaojianhua@gmail.com&Passwd=64737210"start iexplore.exe http://www.google.com
start iexplore.exe http://www.baidu.com
start iexplore.exe http://exchange2003
i learn some stuff like:
start iexplore.exe url is used to open a browser with a given url
& in url is refer some variables in dynamic web, like jsp, asp, etc after ?
^ is used to escape the special char like &. we use \ in unix shell
we can do as in shell script using "" to quoto a statement, and in this quote we use %% to escape %
find out interface:
useing firefox to find out the infor of that form or post, then check out the post or ref with variable. there should be some encode, follow that and finish the whole url.
here is a easy .bat for opening several webs:
start iexplore.exe http://shaojianhua.bloggerspaces.com
start iexplore.exe http://dict.baidu.com
start iexplore.exe "https://www.google.com/accounts/ServiceLoginBoxAuth?continue=http%%3A%%2F%%2Fwww.blogger.com%%
2Floginz%%3Fd%%3D%%
252Fstart&service=blogger&nui=8&naui=8&fpui=2&uilel=3&skipvpage=true&rm=false&hl=zh_CN&alwf=true&roeu=https%%3A%%
2F%%2Fwww.blogger.com%%2Flogin.g&GA3T=H4Ef6yxjXys&Email=dustin.shaojianhua@gmail.com&Passwd=64737210"start iexplore.exe http://www.google.com
start iexplore.exe http://www.baidu.com
start iexplore.exe http://exchange2003
Monday, 21 May 2007
HTTP Made Really Easy
How the web works: HTTP and CGI explained
HTTP Made Really Easy
A Practical Guide to Writing Clients and Servers
Home > Web Technology Made Really Easy > HTTP Made Really Easy
Donate
--------------------------------------------------------------------------------
Table of Contents | Footnotes
--------------------------------------------------------------------------------
HTTP is the network protocol of the Web. It is both simple and powerful. Knowing HTTP enables you to write Web browsers, Web servers, automatic page downloaders, link-checkers, and other useful tools.
This tutorial explains the simple, English-based structure of HTTP communication, and teaches you the practical details of writing HTTP clients and servers. It assumes you know basic socket programming. HTTP is simple enough for a beginning sockets programmer, so this page might be a good followup to a sockets tutorial. This Sockets FAQ (hint: see "Categorized Questions" section at bottom) focuses on C, but the underlying concepts are language-independent.
Since you're reading this, you probably already use CGI. If not, it makes sense to learn that first.
The whole tutorial is about 15 printed pages long, including examples. The first half explains basic HTTP 1.0, and the second half explains the new requirements and features of HTTP 1.1. This tutorial doesn't cover everything about HTTP; it explains the basic framework, how to comply with the requirements, and where to find out more when you need it. If you plan to use HTTP extensively, you should read the specification as well-- see the end of this document for more details.
Before getting started, understand the following two paragraphs:
Writing HTTP or other network programs requires more care than programming for a single machine. Of course, you have to follow standards, or no one will understand you. But even more important is the burden you place on other machines. Write a bad program for your own machine, and you waste your own resources (CPU time, bandwidth, memory). Write a bad network program, and you waste other people's resources. Write a really bad network program, and you waste many thousands of people's resources at the same time. Sloppy and malicious network programming forces network standards to be modified, made safer but less efficient. So be careful, respectful, and cooperative, for everyone's sake.
In particular, don't be tempted to write programs that automatically follow Web links (called robots or spiders) before you really know what you're doing. They can be useful, but a badly-written robot is one of the worst kinds of programs on the Web, blindly following a rapidly increasing number of links and quickly draining server resources. If you plan to write anything like a robot, please read more about them. There may already be a working program to do what you want. If you really need to write your own, read these guidelines. Definitely support the current Standard for Robot Exclusion, and stay tuned for further developments.
OK, enough of that. Let's get started.
--------------------------------------------------------------------------------
Table of Contents
Top of Page
Using HTTP 1.0
What is HTTP?
What are "Resources"?
Structure of HTTP Transactions
Initial Request Line
Initial Response Line (Status Line)
Header Lines
The Message Body
Sample HTTP Exchange
Other HTTP Methods, Like HEAD and POST
The HEAD Method
The POST Method
HTTP Proxies
Being Tolerant of Others
Conclusion
Upgrading to HTTP 1.1
HTTP 1.1
HTTP 1.1 Clients
Host: Header
Chunked Transfer-Encoding
Persistent Connections and the "Connection: close" Header
The "100 Continue" Response
HTTP 1.1 Servers
Requiring the Host: Header
Accepting Absolute URL's
Chunked Transfer-Encoding
Persistent Connections and the "Connection: close" Header
Using the "100 Continue" Response
The Date: Header
Handling Requests with If-Modified-Since: or If-Unmodified-Since: Headers
Supporting the GET and HEAD methods
Supporting HTTP 1.0 Requests
Appendix
The HTTP Specification
Several related topics are discussed on a "footnotes" page:
Sample HTTP Client
Using GET to Submit Query or Form Data
URL-encoding
Manually Experimenting with HTTP
--------------------------------------------------------------------------------
What is HTTP?
HTTP stands for Hypertext Transfer Protocol. It's the network protocol used to deliver virtually all files and other data (collectively called resources) on the World Wide Web, whether they're HTML files, image files, query results, or anything else. Usually, HTTP takes place through TCP/IP sockets (and this tutorial ignores other possibilities).
A browser is an HTTP client because it sends requests to an HTTP server (Web server), which then sends responses back to the client. The standard (and default) port for HTTP servers to listen on is 80, though they can use any port.
What are "Resources"?
HTTP is used to transmit resources, not just files. A resource is some chunk of information that can be identified by a URL (it's the R in URL). The most common kind of resource is a file, but a resource may also be a dynamically-generated query result, the output of a CGI script, a document that is available in several languages, or something else.
While learning HTTP, it may help to think of a resource as similar to a file, but more general. As a practical matter, almost all HTTP resources are currently either files or server-side script output.
Return to Table of Contents
--------------------------------------------------------------------------------
Structure of HTTP Transactions
Like most network protocols, HTTP uses the client-server model: An HTTP client opens a connection and sends a request message to an HTTP server; the server then returns a response message, usually containing the resource that was requested. After delivering the response, the server closes the connection (making HTTP a stateless protocol, i.e. not maintaining any connection information between transactions).
The format of the request and response messages are similar, and English-oriented. Both kinds of messages consist of:
an initial line,
zero or more header lines,
a blank line (i.e. a CRLF by itself), and
an optional message body (e.g. a file, or query data, or query output).
Put another way, the format of an HTTP message is:
Header1: value1
Header2: value2
Header3: value3
it can be many lines long, or even binary data $&*%@!^$@>
Initial lines and headers should end in CRLF, though you should gracefully handle lines ending in just LF. (More exactly, CR and LF here mean ASCII values 13 and 10, even though some platforms may use different characters.)
Return to Table of Contents
Initial Request Line
The initial line is different for the request than for the response. A request line has three parts, separated by spaces: a method name, the local path of the requested resource, and the version of HTTP being used. A typical request line is:
GET /path/to/file/index.html HTTP/1.0
Notes:
GET is the most common HTTP method; it says "give me this resource". Other methods include POST and HEAD-- more on those later. Method names are always uppercase.
The path is the part of the URL after the host name, also called the request URI (a URI is like a URL, but more general).
The HTTP version always takes the form "HTTP/x.x", uppercase.
Return to Table of Contents
Initial Response Line (Status Line)
The initial response line, called the status line, also has three parts separated by spaces: the HTTP version, a response status code that gives the result of the request, and an English reason phrase describing the status code. Typical status lines are:
HTTP/1.0 200 OK
or
HTTP/1.0 404 Not Found
Notes:
The HTTP version is in the same format as in the request line, "HTTP/x.x".
The status code is meant to be computer-readable; the reason phrase is meant to be human-readable, and may vary.
The status code is a three-digit integer, and the first digit identifies the general category of response:
1xx indicates an informational message only
2xx indicates success of some kind
3xx redirects the client to another URL
4xx indicates an error on the client's part
5xx indicates an error on the server's part
The most common status codes are:
200 OK
The request succeeded, and the resulting resource (e.g. file or script output) is returned in the message body.
404 Not Found
The requested resource doesn't exist.
301 Moved Permanently
302 Moved Temporarily
303 See Other (HTTP 1.1 only)
The resource has moved to another URL (given by the Location: response header), and should be automatically retrieved by the client. This is often used by a CGI script to redirect the browser to an existing file.
500 Server Error
An unexpected server error. The most common cause is a server-side script that has bad syntax, fails, or otherwise can't run correctly.
A complete list of status codes is in the HTTP specification (section 9 for HTTP 1.0, and section 10 for HTTP 1.1).
Return to Table of Contents
Header Lines
Header lines provide information about the request or response, or about the object sent in the message body.
The header lines are in the usual text header format, which is: one line per header, of the form "Header-Name: value", ending with CRLF. It's the same format used for email and news postings, defined in RFC 822, section 3. Details about RFC 822 header lines:
As noted above, they should end in CRLF, but you should handle LF correctly.
The header name is not case-sensitive (though the value may be).
Any number of spaces or tabs may be between the ":" and the value.
Header lines beginning with space or tab are actually part of the previous header line, folded into multiple lines for easy reading.
Thus, the following two headers are equivalent:
Header1: some-long-value-1a, some-long-value-1b
HEADER1: some-long-value-1a,
some-long-value-1b
HTTP 1.0 defines 16 headers, though none are required. HTTP 1.1 defines 46 headers, and one (Host:) is required in requests. For Net-politeness, consider including these headers in your requests:
The From: header gives the email address of whoever's making the request, or running the program doing so. (This must be user-configurable, for privacy concerns.)
The User-Agent: header identifies the program that's making the request, in the form "Program-name/x.xx", where x.xx is the (mostly) alphanumeric version of the program. For example, Netscape 3.0 sends the header "User-agent: Mozilla/3.0Gold".
These headers help webmasters troubleshoot problems. They also reveal information about the user. When you decide which headers to include, you must balance the webmasters' logging needs against your users' needs for privacy.
If you're writing servers, consider including these headers in your responses:
The Server: header is analogous to the User-Agent: header: it identifies the server software in the form "Program-name/x.xx". For example, one beta version of Apache's server returns "Server: Apache/1.2b3-dev".
The Last-Modified: header gives the modification date of the resource that's being returned. It's used in caching and other bandwidth-saving activities. Use Greenwich Mean Time, in the format
Last-Modified: Fri, 31 Dec 1999 23:59:59 GMT
Return to Table of Contents
The Message Body
An HTTP message may have a body of data sent after the header lines. In a response, this is where the requested resource is returned to the client (the most common use of the message body), or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server.
If an HTTP message includes a body, there are usually header lines in the message that describe the body. In particular,
The Content-Type: header gives the MIME-type of the data in the body, such as text/html or image/gif.
The Content-Length: header gives the number of bytes in the body.
Return to Table of Contents
--------------------------------------------------------------------------------
Sample HTTP Exchange
To retrieve the file at the URL
http://www.somehost.com/path/file.html
first open a socket to the host www.somehost.com, port 80 (use the default port of 80 because none is specified in the URL). Then, send something like the following through the socket:
GET /path/file.html HTTP/1.0
From: someuser@jmarshall.com
User-Agent: HTTPTool/1.0
[blank line here]
The server should respond with something like the following, sent back through the same socket:
HTTP/1.0 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/html
Content-Length: 1354
(more file contents)
.
.
.
After sending the response, the server closes the socket.
To familiarize yourself with requests and responses, manually experiment with HTTP using telnet.
Return to Table of Contents
--------------------------------------------------------------------------------
Other HTTP Methods, Like HEAD and POST
Besides GET, the two most commonly used methods are HEAD and POST.
The HEAD Method
A HEAD request is just like a GET request, except it asks the server to return the response headers only, and not the actual resource (i.e. no message body). This is useful to check characteristics of a resource without actually downloading it, thus saving bandwidth. Use HEAD when you don't actually need a file's contents.
The response to a HEAD request must never contain a message body, just the status line and headers.
Return to Table of Contents
The POST Method
A POST request is used to send data to the server to be processed in some way, like by a CGI script. A POST request is different from a GET request in the following ways:
There's a block of data sent with the request, in the message body. There are usually extra headers to describe this message body, like Content-Type: and Content-Length:.
The request URI is not a resource to retrieve; it's usually a program to handle the data you're sending.
The HTTP response is normally program output, not a static file.
The most common use of POST, by far, is to submit HTML form data to CGI scripts. In this case, the Content-Type: header is usually application/x-www-form-urlencoded, and the Content-Length: header gives the length of the URL-encoded form data (here's a note on URL-encoding). The CGI script receives the message body through STDIN, and decodes it. Here's a typical form submission, using POST:
POST /path/script.cgi HTTP/1.0
From: frog@jmarshall.com
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
home=Cosby&favorite+flavor=flies
You can use a POST request to send whatever data you want, not just form submissions. Just make sure the sender and the receiving program agree on the format.
The GET method can also be used to submit forms. The form data is URL-encoded and appended to the request URI. Here are more details.
If you're writing HTTP servers that support CGI scripts, you should read the NCSA's CGI definition if you haven't already, especially which environment variables you need to pass to the scripts.
Return to Table of Contents
--------------------------------------------------------------------------------
HTTP Proxies
An HTTP proxy is a program that acts as an intermediary between a client and a server. It receives requests from clients, and forwards those requests to the intended servers. The responses pass back through it in the same way. Thus, a proxy has functions of both a client and a server.
Proxies are commonly used in firewalls, for LAN-wide caches, or in other situations. If you're writing proxies, read the HTTP specification; it contains details about proxies not covered in this tutorial.
When a client uses a proxy, it typically sends all requests to that proxy, instead of to the servers in the URLs. Requests to a proxy differ from normal requests in one way: in the first line, they use the complete URL of the resource being requested, instead of just the path. For example,
GET http://www.somehost.com/path/file.html HTTP/1.0
That way, the proxy knows which server to forward the request to (though the proxy itself may use another proxy).
Return to Table of Contents
--------------------------------------------------------------------------------
Being Tolerant of Others
As the saying goes (in network programming, anyway), "Be strict in what you send and tolerant in what you receive." Other clients and servers you interact with may have minor flaws in their messages, but you should try to work gracefully with them. In particular, the HTTP specification suggests the following:
Even though header lines should end with CRLF, someone might use a single LF instead. Accept either CRLF or LF.
The three fields in the initial message line should be separated by a single space, but might instead use several spaces, or tabs. Accept any number of spaces or tabs between these fields.
The specification has other suggestions too, like how to handle varying date formats. If your program interprets dates from other programs, read the "Tolerant Applications" section of the specification.
Return to Table of Contents
--------------------------------------------------------------------------------
Conclusion
That's the basic structure of HTTP. If you understand everything so far, you have a good overview of HTTP communication, and should be able to write simple HTTP 1.0 programs. See this example to get started. Again, before you do anything heavy-duty, read the specification.
The rest of this document tells how to upgrade your clients and servers to use HTTP 1.1. There is a list of new client requirements, and a list of new server requirements. You can stop here if HTTP 1.0 satisfies your current needs (though you'll probably need HTTP 1.1 in the future).
Note: As of early 1997, the Web is moving from HTTP 1.0 to HTTP 1.1. Whenever practical, use HTTP 1.1. It's more efficient overall, and by using it, you'll help the Web perform better for everyone.
--------------------------------------------------------------------------------
HTTP 1.1
Like many protocols, HTTP is constantly evolving. HTTP 1.1 has recently been defined, to address new needs and overcome shortcomings of HTTP 1.0. Generally speaking, it is a superset of HTTP 1.0. Improvements include:
Faster response, by allowing multiple transactions to take place over a single persistent connection.
Faster response and great bandwidth savings, by adding cache support.
Faster response for dynamically-generated pages, by supporting chunked encoding, which allows a response to be sent before its total length is known.
Efficient use of IP addresses, by allowing multiple domains to be served from a single IP address.
HTTP 1.1 requires a few extra things from both clients and servers. The next two sections detail how to make clients and servers comply with HTTP 1.1. If you're only writing clients, you can skip the section on servers. If you're writing servers, read both sections.
Only requirements for HTTP 1.1 compliance are described here. HTTP 1.1 has many optional features you may find useful; read the specification to learn more.
Return to Table of Contents
--------------------------------------------------------------------------------
HTTP 1.1 Clients
To comply with HTTP 1.1, clients must
include the Host: header with each request
accept responses with chunked data
either support persistent connections, or include the "Connection: close" header with each request
handle the "100 Continue" response
Return to Table of Contents
Host: Header
Starting with HTTP 1.1, one server at one IP address can be multi-homed, i.e. the home of several Web domains. For example, "www.host1.com" and "www.host2.com" can live on the same server.
Several domains living on the same server is like several people sharing one phone: a caller knows who they're calling for, but whoever answers the phone doesn't. Thus, every HTTP request must specify which host name (and possibly port) the request is intended for, with the Host: header. A complete HTTP 1.1 request might be
GET /path/file.html HTTP/1.1
Host: www.host1.com:80
[blank line here]
except the ":80" isn't required, since that's the default HTTP port.
Host: is the only required header in an HTTP 1.1 request. It's also the most urgently needed new feature in HTTP 1.1. Without it, each host name requires a unique IP address, and we're quickly running out of IP addresses with the explosion of new domains.
Return to Table of Contents
Chunked Transfer-Encoding
If a server wants to start sending a response before knowing its total length (like with long script output), it might use the simple chunked transfer-encoding, which breaks the complete response into smaller chunks and sends them in series. You can identify such a response because it contains the "Transfer-Encoding: chunked" header. All HTTP 1.1 clients must be able to receive chunked messages.
A chunked message body contains a series of chunks, followed by a line with "0" (zero), followed by optional footers (just like headers), and a blank line. Each chunk consists of two parts:
a line with the size of the chunk data, in hex, possibly followed by a semicolon and extra parameters you can ignore (none are currently standard), and ending with CRLF.
the data itself, followed by CRLF.
So a chunked response might look like the following:
HTTP/1.1 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
1a; ignore-stuff-here
abcdefghijklmnopqrstuvwxyz
10
1234567890abcdef
0
some-footer: some-value
another-footer: another-value
[blank line here]
Note the blank line after the last footer. The length of the text data is 42 bytes (1a + 10, in hex), and the data itself is abcdefghijklmnopqrstuvwxyz1234567890abcdef. The footers should be treated like headers, as if they were at the top of the response.
The chunks can contain any binary data, and may be much larger than the examples here. The size-line parameters are rarely used, but you should at least ignore them correctly. Footers are also rare, but might be appropriate for things like checksums or digital signatures.
For comparison, here's the equivalent to the above response, without using chunked encoding:
HTTP/1.1 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/plain
Content-Length: 42
some-footer: some-value
another-footer: another-value
abcdefghijklmnopqrstuvwxyz1234567890abcdef
Return to Table of Contents
Persistent Connections and the "Connection: close" Header
In HTTP 1.0 and before, TCP connections are closed after each request and response, so each resource to be retrieved requires its own connection. Opening and closing TCP connections takes a substantial amount of CPU time, bandwidth, and memory. In practice, most Web pages consist of several files on the same server, so much can be saved by allowing several requests and responses to be sent through a single persistent connection.
Persistent connections are the default in HTTP 1.1, so nothing special is required to use them. Just open a connection and send several requests in series (called pipelining), and read the responses in the same order as the requests were sent. If you do this, be very careful to read the correct length of each response, to separate them correctly.
If a client includes the "Connection: close" header in the request, then the connection will be closed after the corresponding response. Use this if you don't support persistent connections, or if you know a request will be the last on its connection. Similarly, if a response contains this header, then the server will close the connection following that response, and the client shouldn't send any more requests through that connection.
A server might close the connection before all responses are sent, so a client must keep track of requests and resend them as needed. When resending, don't pipeline the requests until you know the connection is persistent. Don't pipeline at all if you know the server won't support persistent connections (like if it uses HTTP 1.0, based on a previous response).
Return to Table of Contents
The "100 Continue" Response
During the course of an HTTP 1.1 client sending a request to a server, the server might respond with an interim "100 Continue" response. This means the server has received the first part of the request, and can be used to aid communication over slow links. In any case, all HTTP 1.1 clients must handle the 100 response correctly (perhaps by just ignoring it).
The "100 Continue" response is structured like any HTTP response, i.e. consists of a status line, optional headers, and a blank line. Unlike other responses, it is always followed by another complete, final response.
So, further extending the last example, the full data that comes back from the server might consist of two responses in series, like
HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/plain
Content-Length: 42
some-footer: some-value
another-footer: another-value
abcdefghijklmnoprstuvwxyz1234567890abcdef
To handle this, a simple HTTP 1.1 client might read one response from the socket; if the status code is 100, discard the first response and read the next one instead.
Return to Table of Contents
--------------------------------------------------------------------------------
HTTP 1.1 Servers
To comply with HTTP 1.1, servers must:
require the Host: header from HTTP 1.1 clients
accept absolute URL's in a request
accept requests with chunked data
either support persistent connections, or include the "Connection: close" header with each response
use the "100 Continue" response appropriately
include the Date: header in each response
handle requests with If-Modified-Since: or If-Unmodified-Since: headers
support at least the GET and HEAD methods
support HTTP 1.0 requests
Return to Table of Contents
Requiring the Host: Header
Because of the urgency of implementing the new Host: header, servers are not allowed to tolerate HTTP 1.1 requests without it. If a server receives such a request, it must return a "400 Bad Request" response, like
HTTP/1.1 400 Bad Request
Content-Type: text/html
Content-Length: 111
HTTP 1.1 requests must include the Host: header.
This requirement applies only to clients using HTTP 1.1, not any future version of HTTP. If the request uses an HTTP version later than 1.1, the server can accept an absolute URL instead of a Host: header (see next section). If the request uses HTTP 1.0, the server may accept the request without any host identification.
Return to Table of Contents
Accepting Absolute URL's
The Host: header is actually an interim solution to the problem of host identification. In future versions of HTTP, requests will use an absolute URL instead of a pathname, like
GET http://www.somehost.com/path/file.html HTTP/1.2
To enable this protocol transition, HTTP 1.1 servers must accept this form of request, even though HTTP 1.1 clients won't send them. The server must still report an error if an HTTP 1.1 client leaves out the Host: header, as described in the previous section.
Return to Table of Contents
Chunked Transfer-Encoding
Just as HTTP 1.1 clients must accept chunked responses, servers must accept chunked requests (an unlikely scenario, but possible). See the earlier section on HTTP 1.1 Clients for details of the chunked data format.
Servers aren't required to generate chunked messages; they just have to be able to receive them.
Return to Table of Contents
Persistent Connections and the "Connection: close" Header
If an HTTP 1.1 client sends multiple requests through a single connection, the server should send responses back in the same order as the requests-- this is all it takes for a server to support persistent connections.
If a request includes the "Connection: close" header, that request is the final one for the connection and the server should close the connection after sending the response. Also, the server should close an idle connection after some timeout period (can be anything; 10 seconds is fine).
If you don't want to support persistent connections, include the "Connection: close" header in the response. Use this header whenever you want to close the connection, even if not all requests have been fulfilled. The header says that the connection will be closed after the current response, and a valid HTTP 1.1 client will handle it correctly.
Return to Table of Contents
Using the "100 Continue" Response
As described in the section on HTTP 1.1 Clients, this response exists to help deal with slow links.
When an HTTP 1.1 server receives the first line of an HTTP 1.1 (or later) request, it must respond with either "100 Continue" or an error. If it sends the "100 Continue" response, it must also send another, final response, once the request has been processed. The "100 Continue" response requires no headers, but must be followed by the usual blank line, like:
HTTP/1.1 100 Continue
[blank line here]
[another HTTP response will go here]
Don't send "100 Continue" to HTTP 1.0 clients, since they don't know how to handle it.
Return to Table of Contents
The Date: Header
Caching is an important improvement in HTTP 1.1, and can't work without timestamped responses. So, servers must timestamp every response with a Date: header containing the current time, in the form
Date: Fri, 31 Dec 1999 23:59:59 GMT
All responses except those with 100-level status (but including error responses) must include the Date: header.
All time values in HTTP use Greenwich Mean Time.
Return to Table of Contents
Handling Requests with If-Modified-Since: or If-Unmodified-Since: Headers
To avoid sending resources that don't need to be sent, thus saving bandwidth, HTTP 1.1 defines the If-Modified-Since: and If-Unmodified-Since: request headers. The former says "only send the resource if it has changed since this date"; the latter says the opposite. Clients aren't required to use them, but HTTP 1.1 servers are required to honor requests that do use them.
Unfortunately, due to earlier HTTP versions, the date value may be in any of three possible formats:
If-Modified-Since: Fri, 31 Dec 1999 23:59:59 GMT
If-Modified-Since: Friday, 31-Dec-99 23:59:59 GMT
If-Modified-Since: Fri Dec 31 23:59:59 1999
Again, all time values in HTTP use Greenwich Mean Time (though try to be tolerant of non-GMT times). If a date with a two-digit year seems to be more than 50 years in the future, treat it as being in the past-- this helps with the millennium bug. In fact, do this with any date handling in HTTP 1.1.
Although servers must accept all three date formats, HTTP 1.1 clients and servers must only generate the first kind.
If the date in either of these headers is invalid, or is in the future, ignore the header.
If, without the header, the request would result in an unsuccessful (non-200-level) status code, ignore the header and send the non-200-level response. In other words, only apply these headers when you know the resource would otherwise be sent.
The If-Modified-Since: header is used with a GET request. If the requested resource has been modified since the given date, ignore the header and return the resource as you normally would. Otherwise, return a "304 Not Modified" response, including the Date: header and no message body, like
HTTP/1.1 304 Not Modified
Date: Fri, 31 Dec 1999 23:59:59 GMT
[blank line here]
The If-Unmodified-Since: header is similar, but can be used with any method. If the requested resource has not been modified since the given date, ignore the header and return the resource as you normally would. Otherwise, return a "412 Precondition Failed" response, like
HTTP/1.1 412 Precondition Failed
[blank line here]
Return to Table of Contents
Supporting the GET and HEAD methods
To comply with HTTP 1.1, a server must support at least the GET and HEAD methods. If you're handling CGI scripts, you should probably support the POST method too.
Four other methods (PUT, DELETE, OPTIONS, and TRACE) are defined in HTTP 1.1, but are rarely used. If a client requests a method you don't support, respond with "501 Not Implemented", like
HTTP/1.1 501 Not Implemented
[blank line here]
Return to Table of Contents
Supporting HTTP 1.0 Requests
To be compatible with older browsers, HTTP 1.1 servers must support HTTP 1.0 requests. In particular, when a request uses HTTP 1.0 (as identified in the initial request line),
don't require the Host: header, and
don't send the "100 Continue" response.
Return to Table of Contents
--------------------------------------------------------------------------------
The HTTP Specification
If you plan to do anything elaborate in HTTP, read the official specification. HTTP 1.0 was never made an official Internet standard, but the de facto standard is described in RFC 1945. HTTP 1.1 was developed by a working group of the IETF, openly gathering input from many sources before reaching an approximate consensus. The resulting specification is RFC 2616, released in June 1999.
These documents are available in various formats:
HTTP 1.0 (RFC 1945)-- HTML, text, and gzip'd PostScript
HTTP 1.1 (RFC 2616)-- HTML, text, PostScript, and PDF.
Download and print the version you'll be using, for reference and bedtime reading.
The World Wide Web Consortium has a page devoted to HTTP including news and updates, and a page listing HTTP specifications, drafts, and reports.
Other RFC's you might find useful:
RFC 822-- structure of Internet text messages, including header fields
RFC 2396-- definition of URL/URI syntax (replaces RFC 1738 and RFC 1808)
RFC 1521-- definition of MIME and of MIME types
Return to Table of Contents
--------------------------------------------------------------------------------
© 1997 James Marshall (comments welcome)
Last (significantly) modified: August 15, 1997 http://www.jmarshall.com/easy/http/
HTTP Made Really Easy
A Practical Guide to Writing Clients and Servers
Home > Web Technology Made Really Easy > HTTP Made Really Easy
Donate
--------------------------------------------------------------------------------
Table of Contents | Footnotes
--------------------------------------------------------------------------------
HTTP is the network protocol of the Web. It is both simple and powerful. Knowing HTTP enables you to write Web browsers, Web servers, automatic page downloaders, link-checkers, and other useful tools.
This tutorial explains the simple, English-based structure of HTTP communication, and teaches you the practical details of writing HTTP clients and servers. It assumes you know basic socket programming. HTTP is simple enough for a beginning sockets programmer, so this page might be a good followup to a sockets tutorial. This Sockets FAQ (hint: see "Categorized Questions" section at bottom) focuses on C, but the underlying concepts are language-independent.
Since you're reading this, you probably already use CGI. If not, it makes sense to learn that first.
The whole tutorial is about 15 printed pages long, including examples. The first half explains basic HTTP 1.0, and the second half explains the new requirements and features of HTTP 1.1. This tutorial doesn't cover everything about HTTP; it explains the basic framework, how to comply with the requirements, and where to find out more when you need it. If you plan to use HTTP extensively, you should read the specification as well-- see the end of this document for more details.
Before getting started, understand the following two paragraphs:
Writing HTTP or other network programs requires more care than programming for a single machine. Of course, you have to follow standards, or no one will understand you. But even more important is the burden you place on other machines. Write a bad program for your own machine, and you waste your own resources (CPU time, bandwidth, memory). Write a bad network program, and you waste other people's resources. Write a really bad network program, and you waste many thousands of people's resources at the same time. Sloppy and malicious network programming forces network standards to be modified, made safer but less efficient. So be careful, respectful, and cooperative, for everyone's sake.
In particular, don't be tempted to write programs that automatically follow Web links (called robots or spiders) before you really know what you're doing. They can be useful, but a badly-written robot is one of the worst kinds of programs on the Web, blindly following a rapidly increasing number of links and quickly draining server resources. If you plan to write anything like a robot, please read more about them. There may already be a working program to do what you want. If you really need to write your own, read these guidelines. Definitely support the current Standard for Robot Exclusion, and stay tuned for further developments.
OK, enough of that. Let's get started.
--------------------------------------------------------------------------------
Table of Contents
Top of Page
Using HTTP 1.0
What is HTTP?
What are "Resources"?
Structure of HTTP Transactions
Initial Request Line
Initial Response Line (Status Line)
Header Lines
The Message Body
Sample HTTP Exchange
Other HTTP Methods, Like HEAD and POST
The HEAD Method
The POST Method
HTTP Proxies
Being Tolerant of Others
Conclusion
Upgrading to HTTP 1.1
HTTP 1.1
HTTP 1.1 Clients
Host: Header
Chunked Transfer-Encoding
Persistent Connections and the "Connection: close" Header
The "100 Continue" Response
HTTP 1.1 Servers
Requiring the Host: Header
Accepting Absolute URL's
Chunked Transfer-Encoding
Persistent Connections and the "Connection: close" Header
Using the "100 Continue" Response
The Date: Header
Handling Requests with If-Modified-Since: or If-Unmodified-Since: Headers
Supporting the GET and HEAD methods
Supporting HTTP 1.0 Requests
Appendix
The HTTP Specification
Several related topics are discussed on a "footnotes" page:
Sample HTTP Client
Using GET to Submit Query or Form Data
URL-encoding
Manually Experimenting with HTTP
--------------------------------------------------------------------------------
What is HTTP?
HTTP stands for Hypertext Transfer Protocol. It's the network protocol used to deliver virtually all files and other data (collectively called resources) on the World Wide Web, whether they're HTML files, image files, query results, or anything else. Usually, HTTP takes place through TCP/IP sockets (and this tutorial ignores other possibilities).
A browser is an HTTP client because it sends requests to an HTTP server (Web server), which then sends responses back to the client. The standard (and default) port for HTTP servers to listen on is 80, though they can use any port.
What are "Resources"?
HTTP is used to transmit resources, not just files. A resource is some chunk of information that can be identified by a URL (it's the R in URL). The most common kind of resource is a file, but a resource may also be a dynamically-generated query result, the output of a CGI script, a document that is available in several languages, or something else.
While learning HTTP, it may help to think of a resource as similar to a file, but more general. As a practical matter, almost all HTTP resources are currently either files or server-side script output.
Return to Table of Contents
--------------------------------------------------------------------------------
Structure of HTTP Transactions
Like most network protocols, HTTP uses the client-server model: An HTTP client opens a connection and sends a request message to an HTTP server; the server then returns a response message, usually containing the resource that was requested. After delivering the response, the server closes the connection (making HTTP a stateless protocol, i.e. not maintaining any connection information between transactions).
The format of the request and response messages are similar, and English-oriented. Both kinds of messages consist of:
an initial line,
zero or more header lines,
a blank line (i.e. a CRLF by itself), and
an optional message body (e.g. a file, or query data, or query output).
Put another way, the format of an HTTP message is:
Header1: value1
Header2: value2
Header3: value3
Initial lines and headers should end in CRLF, though you should gracefully handle lines ending in just LF. (More exactly, CR and LF here mean ASCII values 13 and 10, even though some platforms may use different characters.)
Return to Table of Contents
Initial Request Line
The initial line is different for the request than for the response. A request line has three parts, separated by spaces: a method name, the local path of the requested resource, and the version of HTTP being used. A typical request line is:
GET /path/to/file/index.html HTTP/1.0
Notes:
GET is the most common HTTP method; it says "give me this resource". Other methods include POST and HEAD-- more on those later. Method names are always uppercase.
The path is the part of the URL after the host name, also called the request URI (a URI is like a URL, but more general).
The HTTP version always takes the form "HTTP/x.x", uppercase.
Return to Table of Contents
Initial Response Line (Status Line)
The initial response line, called the status line, also has three parts separated by spaces: the HTTP version, a response status code that gives the result of the request, and an English reason phrase describing the status code. Typical status lines are:
HTTP/1.0 200 OK
or
HTTP/1.0 404 Not Found
Notes:
The HTTP version is in the same format as in the request line, "HTTP/x.x".
The status code is meant to be computer-readable; the reason phrase is meant to be human-readable, and may vary.
The status code is a three-digit integer, and the first digit identifies the general category of response:
1xx indicates an informational message only
2xx indicates success of some kind
3xx redirects the client to another URL
4xx indicates an error on the client's part
5xx indicates an error on the server's part
The most common status codes are:
200 OK
The request succeeded, and the resulting resource (e.g. file or script output) is returned in the message body.
404 Not Found
The requested resource doesn't exist.
301 Moved Permanently
302 Moved Temporarily
303 See Other (HTTP 1.1 only)
The resource has moved to another URL (given by the Location: response header), and should be automatically retrieved by the client. This is often used by a CGI script to redirect the browser to an existing file.
500 Server Error
An unexpected server error. The most common cause is a server-side script that has bad syntax, fails, or otherwise can't run correctly.
A complete list of status codes is in the HTTP specification (section 9 for HTTP 1.0, and section 10 for HTTP 1.1).
Return to Table of Contents
Header Lines
Header lines provide information about the request or response, or about the object sent in the message body.
The header lines are in the usual text header format, which is: one line per header, of the form "Header-Name: value", ending with CRLF. It's the same format used for email and news postings, defined in RFC 822, section 3. Details about RFC 822 header lines:
As noted above, they should end in CRLF, but you should handle LF correctly.
The header name is not case-sensitive (though the value may be).
Any number of spaces or tabs may be between the ":" and the value.
Header lines beginning with space or tab are actually part of the previous header line, folded into multiple lines for easy reading.
Thus, the following two headers are equivalent:
Header1: some-long-value-1a, some-long-value-1b
HEADER1: some-long-value-1a,
some-long-value-1b
HTTP 1.0 defines 16 headers, though none are required. HTTP 1.1 defines 46 headers, and one (Host:) is required in requests. For Net-politeness, consider including these headers in your requests:
The From: header gives the email address of whoever's making the request, or running the program doing so. (This must be user-configurable, for privacy concerns.)
The User-Agent: header identifies the program that's making the request, in the form "Program-name/x.xx", where x.xx is the (mostly) alphanumeric version of the program. For example, Netscape 3.0 sends the header "User-agent: Mozilla/3.0Gold".
These headers help webmasters troubleshoot problems. They also reveal information about the user. When you decide which headers to include, you must balance the webmasters' logging needs against your users' needs for privacy.
If you're writing servers, consider including these headers in your responses:
The Server: header is analogous to the User-Agent: header: it identifies the server software in the form "Program-name/x.xx". For example, one beta version of Apache's server returns "Server: Apache/1.2b3-dev".
The Last-Modified: header gives the modification date of the resource that's being returned. It's used in caching and other bandwidth-saving activities. Use Greenwich Mean Time, in the format
Last-Modified: Fri, 31 Dec 1999 23:59:59 GMT
Return to Table of Contents
The Message Body
An HTTP message may have a body of data sent after the header lines. In a response, this is where the requested resource is returned to the client (the most common use of the message body), or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server.
If an HTTP message includes a body, there are usually header lines in the message that describe the body. In particular,
The Content-Type: header gives the MIME-type of the data in the body, such as text/html or image/gif.
The Content-Length: header gives the number of bytes in the body.
Return to Table of Contents
--------------------------------------------------------------------------------
Sample HTTP Exchange
To retrieve the file at the URL
http://www.somehost.com/path/file.html
first open a socket to the host www.somehost.com, port 80 (use the default port of 80 because none is specified in the URL). Then, send something like the following through the socket:
GET /path/file.html HTTP/1.0
From: someuser@jmarshall.com
User-Agent: HTTPTool/1.0
[blank line here]
The server should respond with something like the following, sent back through the same socket:
HTTP/1.0 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/html
Content-Length: 1354
Happy New Millennium!
(more file contents)
.
.
.
After sending the response, the server closes the socket.
To familiarize yourself with requests and responses, manually experiment with HTTP using telnet.
Return to Table of Contents
--------------------------------------------------------------------------------
Other HTTP Methods, Like HEAD and POST
Besides GET, the two most commonly used methods are HEAD and POST.
The HEAD Method
A HEAD request is just like a GET request, except it asks the server to return the response headers only, and not the actual resource (i.e. no message body). This is useful to check characteristics of a resource without actually downloading it, thus saving bandwidth. Use HEAD when you don't actually need a file's contents.
The response to a HEAD request must never contain a message body, just the status line and headers.
Return to Table of Contents
The POST Method
A POST request is used to send data to the server to be processed in some way, like by a CGI script. A POST request is different from a GET request in the following ways:
There's a block of data sent with the request, in the message body. There are usually extra headers to describe this message body, like Content-Type: and Content-Length:.
The request URI is not a resource to retrieve; it's usually a program to handle the data you're sending.
The HTTP response is normally program output, not a static file.
The most common use of POST, by far, is to submit HTML form data to CGI scripts. In this case, the Content-Type: header is usually application/x-www-form-urlencoded, and the Content-Length: header gives the length of the URL-encoded form data (here's a note on URL-encoding). The CGI script receives the message body through STDIN, and decodes it. Here's a typical form submission, using POST:
POST /path/script.cgi HTTP/1.0
From: frog@jmarshall.com
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
home=Cosby&favorite+flavor=flies
You can use a POST request to send whatever data you want, not just form submissions. Just make sure the sender and the receiving program agree on the format.
The GET method can also be used to submit forms. The form data is URL-encoded and appended to the request URI. Here are more details.
If you're writing HTTP servers that support CGI scripts, you should read the NCSA's CGI definition if you haven't already, especially which environment variables you need to pass to the scripts.
Return to Table of Contents
--------------------------------------------------------------------------------
HTTP Proxies
An HTTP proxy is a program that acts as an intermediary between a client and a server. It receives requests from clients, and forwards those requests to the intended servers. The responses pass back through it in the same way. Thus, a proxy has functions of both a client and a server.
Proxies are commonly used in firewalls, for LAN-wide caches, or in other situations. If you're writing proxies, read the HTTP specification; it contains details about proxies not covered in this tutorial.
When a client uses a proxy, it typically sends all requests to that proxy, instead of to the servers in the URLs. Requests to a proxy differ from normal requests in one way: in the first line, they use the complete URL of the resource being requested, instead of just the path. For example,
GET http://www.somehost.com/path/file.html HTTP/1.0
That way, the proxy knows which server to forward the request to (though the proxy itself may use another proxy).
Return to Table of Contents
--------------------------------------------------------------------------------
Being Tolerant of Others
As the saying goes (in network programming, anyway), "Be strict in what you send and tolerant in what you receive." Other clients and servers you interact with may have minor flaws in their messages, but you should try to work gracefully with them. In particular, the HTTP specification suggests the following:
Even though header lines should end with CRLF, someone might use a single LF instead. Accept either CRLF or LF.
The three fields in the initial message line should be separated by a single space, but might instead use several spaces, or tabs. Accept any number of spaces or tabs between these fields.
The specification has other suggestions too, like how to handle varying date formats. If your program interprets dates from other programs, read the "Tolerant Applications" section of the specification.
Return to Table of Contents
--------------------------------------------------------------------------------
Conclusion
That's the basic structure of HTTP. If you understand everything so far, you have a good overview of HTTP communication, and should be able to write simple HTTP 1.0 programs. See this example to get started. Again, before you do anything heavy-duty, read the specification.
The rest of this document tells how to upgrade your clients and servers to use HTTP 1.1. There is a list of new client requirements, and a list of new server requirements. You can stop here if HTTP 1.0 satisfies your current needs (though you'll probably need HTTP 1.1 in the future).
Note: As of early 1997, the Web is moving from HTTP 1.0 to HTTP 1.1. Whenever practical, use HTTP 1.1. It's more efficient overall, and by using it, you'll help the Web perform better for everyone.
--------------------------------------------------------------------------------
HTTP 1.1
Like many protocols, HTTP is constantly evolving. HTTP 1.1 has recently been defined, to address new needs and overcome shortcomings of HTTP 1.0. Generally speaking, it is a superset of HTTP 1.0. Improvements include:
Faster response, by allowing multiple transactions to take place over a single persistent connection.
Faster response and great bandwidth savings, by adding cache support.
Faster response for dynamically-generated pages, by supporting chunked encoding, which allows a response to be sent before its total length is known.
Efficient use of IP addresses, by allowing multiple domains to be served from a single IP address.
HTTP 1.1 requires a few extra things from both clients and servers. The next two sections detail how to make clients and servers comply with HTTP 1.1. If you're only writing clients, you can skip the section on servers. If you're writing servers, read both sections.
Only requirements for HTTP 1.1 compliance are described here. HTTP 1.1 has many optional features you may find useful; read the specification to learn more.
Return to Table of Contents
--------------------------------------------------------------------------------
HTTP 1.1 Clients
To comply with HTTP 1.1, clients must
include the Host: header with each request
accept responses with chunked data
either support persistent connections, or include the "Connection: close" header with each request
handle the "100 Continue" response
Return to Table of Contents
Host: Header
Starting with HTTP 1.1, one server at one IP address can be multi-homed, i.e. the home of several Web domains. For example, "www.host1.com" and "www.host2.com" can live on the same server.
Several domains living on the same server is like several people sharing one phone: a caller knows who they're calling for, but whoever answers the phone doesn't. Thus, every HTTP request must specify which host name (and possibly port) the request is intended for, with the Host: header. A complete HTTP 1.1 request might be
GET /path/file.html HTTP/1.1
Host: www.host1.com:80
[blank line here]
except the ":80" isn't required, since that's the default HTTP port.
Host: is the only required header in an HTTP 1.1 request. It's also the most urgently needed new feature in HTTP 1.1. Without it, each host name requires a unique IP address, and we're quickly running out of IP addresses with the explosion of new domains.
Return to Table of Contents
Chunked Transfer-Encoding
If a server wants to start sending a response before knowing its total length (like with long script output), it might use the simple chunked transfer-encoding, which breaks the complete response into smaller chunks and sends them in series. You can identify such a response because it contains the "Transfer-Encoding: chunked" header. All HTTP 1.1 clients must be able to receive chunked messages.
A chunked message body contains a series of chunks, followed by a line with "0" (zero), followed by optional footers (just like headers), and a blank line. Each chunk consists of two parts:
a line with the size of the chunk data, in hex, possibly followed by a semicolon and extra parameters you can ignore (none are currently standard), and ending with CRLF.
the data itself, followed by CRLF.
So a chunked response might look like the following:
HTTP/1.1 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
1a; ignore-stuff-here
abcdefghijklmnopqrstuvwxyz
10
1234567890abcdef
0
some-footer: some-value
another-footer: another-value
[blank line here]
Note the blank line after the last footer. The length of the text data is 42 bytes (1a + 10, in hex), and the data itself is abcdefghijklmnopqrstuvwxyz1234567890abcdef. The footers should be treated like headers, as if they were at the top of the response.
The chunks can contain any binary data, and may be much larger than the examples here. The size-line parameters are rarely used, but you should at least ignore them correctly. Footers are also rare, but might be appropriate for things like checksums or digital signatures.
For comparison, here's the equivalent to the above response, without using chunked encoding:
HTTP/1.1 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/plain
Content-Length: 42
some-footer: some-value
another-footer: another-value
abcdefghijklmnopqrstuvwxyz1234567890abcdef
Return to Table of Contents
Persistent Connections and the "Connection: close" Header
In HTTP 1.0 and before, TCP connections are closed after each request and response, so each resource to be retrieved requires its own connection. Opening and closing TCP connections takes a substantial amount of CPU time, bandwidth, and memory. In practice, most Web pages consist of several files on the same server, so much can be saved by allowing several requests and responses to be sent through a single persistent connection.
Persistent connections are the default in HTTP 1.1, so nothing special is required to use them. Just open a connection and send several requests in series (called pipelining), and read the responses in the same order as the requests were sent. If you do this, be very careful to read the correct length of each response, to separate them correctly.
If a client includes the "Connection: close" header in the request, then the connection will be closed after the corresponding response. Use this if you don't support persistent connections, or if you know a request will be the last on its connection. Similarly, if a response contains this header, then the server will close the connection following that response, and the client shouldn't send any more requests through that connection.
A server might close the connection before all responses are sent, so a client must keep track of requests and resend them as needed. When resending, don't pipeline the requests until you know the connection is persistent. Don't pipeline at all if you know the server won't support persistent connections (like if it uses HTTP 1.0, based on a previous response).
Return to Table of Contents
The "100 Continue" Response
During the course of an HTTP 1.1 client sending a request to a server, the server might respond with an interim "100 Continue" response. This means the server has received the first part of the request, and can be used to aid communication over slow links. In any case, all HTTP 1.1 clients must handle the 100 response correctly (perhaps by just ignoring it).
The "100 Continue" response is structured like any HTTP response, i.e. consists of a status line, optional headers, and a blank line. Unlike other responses, it is always followed by another complete, final response.
So, further extending the last example, the full data that comes back from the server might consist of two responses in series, like
HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/plain
Content-Length: 42
some-footer: some-value
another-footer: another-value
abcdefghijklmnoprstuvwxyz1234567890abcdef
To handle this, a simple HTTP 1.1 client might read one response from the socket; if the status code is 100, discard the first response and read the next one instead.
Return to Table of Contents
--------------------------------------------------------------------------------
HTTP 1.1 Servers
To comply with HTTP 1.1, servers must:
require the Host: header from HTTP 1.1 clients
accept absolute URL's in a request
accept requests with chunked data
either support persistent connections, or include the "Connection: close" header with each response
use the "100 Continue" response appropriately
include the Date: header in each response
handle requests with If-Modified-Since: or If-Unmodified-Since: headers
support at least the GET and HEAD methods
support HTTP 1.0 requests
Return to Table of Contents
Requiring the Host: Header
Because of the urgency of implementing the new Host: header, servers are not allowed to tolerate HTTP 1.1 requests without it. If a server receives such a request, it must return a "400 Bad Request" response, like
HTTP/1.1 400 Bad Request
Content-Type: text/html
Content-Length: 111
No Host: header received
HTTP 1.1 requests must include the Host: header.
This requirement applies only to clients using HTTP 1.1, not any future version of HTTP. If the request uses an HTTP version later than 1.1, the server can accept an absolute URL instead of a Host: header (see next section). If the request uses HTTP 1.0, the server may accept the request without any host identification.
Return to Table of Contents
Accepting Absolute URL's
The Host: header is actually an interim solution to the problem of host identification. In future versions of HTTP, requests will use an absolute URL instead of a pathname, like
GET http://www.somehost.com/path/file.html HTTP/1.2
To enable this protocol transition, HTTP 1.1 servers must accept this form of request, even though HTTP 1.1 clients won't send them. The server must still report an error if an HTTP 1.1 client leaves out the Host: header, as described in the previous section.
Return to Table of Contents
Chunked Transfer-Encoding
Just as HTTP 1.1 clients must accept chunked responses, servers must accept chunked requests (an unlikely scenario, but possible). See the earlier section on HTTP 1.1 Clients for details of the chunked data format.
Servers aren't required to generate chunked messages; they just have to be able to receive them.
Return to Table of Contents
Persistent Connections and the "Connection: close" Header
If an HTTP 1.1 client sends multiple requests through a single connection, the server should send responses back in the same order as the requests-- this is all it takes for a server to support persistent connections.
If a request includes the "Connection: close" header, that request is the final one for the connection and the server should close the connection after sending the response. Also, the server should close an idle connection after some timeout period (can be anything; 10 seconds is fine).
If you don't want to support persistent connections, include the "Connection: close" header in the response. Use this header whenever you want to close the connection, even if not all requests have been fulfilled. The header says that the connection will be closed after the current response, and a valid HTTP 1.1 client will handle it correctly.
Return to Table of Contents
Using the "100 Continue" Response
As described in the section on HTTP 1.1 Clients, this response exists to help deal with slow links.
When an HTTP 1.1 server receives the first line of an HTTP 1.1 (or later) request, it must respond with either "100 Continue" or an error. If it sends the "100 Continue" response, it must also send another, final response, once the request has been processed. The "100 Continue" response requires no headers, but must be followed by the usual blank line, like:
HTTP/1.1 100 Continue
[blank line here]
[another HTTP response will go here]
Don't send "100 Continue" to HTTP 1.0 clients, since they don't know how to handle it.
Return to Table of Contents
The Date: Header
Caching is an important improvement in HTTP 1.1, and can't work without timestamped responses. So, servers must timestamp every response with a Date: header containing the current time, in the form
Date: Fri, 31 Dec 1999 23:59:59 GMT
All responses except those with 100-level status (but including error responses) must include the Date: header.
All time values in HTTP use Greenwich Mean Time.
Return to Table of Contents
Handling Requests with If-Modified-Since: or If-Unmodified-Since: Headers
To avoid sending resources that don't need to be sent, thus saving bandwidth, HTTP 1.1 defines the If-Modified-Since: and If-Unmodified-Since: request headers. The former says "only send the resource if it has changed since this date"; the latter says the opposite. Clients aren't required to use them, but HTTP 1.1 servers are required to honor requests that do use them.
Unfortunately, due to earlier HTTP versions, the date value may be in any of three possible formats:
If-Modified-Since: Fri, 31 Dec 1999 23:59:59 GMT
If-Modified-Since: Friday, 31-Dec-99 23:59:59 GMT
If-Modified-Since: Fri Dec 31 23:59:59 1999
Again, all time values in HTTP use Greenwich Mean Time (though try to be tolerant of non-GMT times). If a date with a two-digit year seems to be more than 50 years in the future, treat it as being in the past-- this helps with the millennium bug. In fact, do this with any date handling in HTTP 1.1.
Although servers must accept all three date formats, HTTP 1.1 clients and servers must only generate the first kind.
If the date in either of these headers is invalid, or is in the future, ignore the header.
If, without the header, the request would result in an unsuccessful (non-200-level) status code, ignore the header and send the non-200-level response. In other words, only apply these headers when you know the resource would otherwise be sent.
The If-Modified-Since: header is used with a GET request. If the requested resource has been modified since the given date, ignore the header and return the resource as you normally would. Otherwise, return a "304 Not Modified" response, including the Date: header and no message body, like
HTTP/1.1 304 Not Modified
Date: Fri, 31 Dec 1999 23:59:59 GMT
[blank line here]
The If-Unmodified-Since: header is similar, but can be used with any method. If the requested resource has not been modified since the given date, ignore the header and return the resource as you normally would. Otherwise, return a "412 Precondition Failed" response, like
HTTP/1.1 412 Precondition Failed
[blank line here]
Return to Table of Contents
Supporting the GET and HEAD methods
To comply with HTTP 1.1, a server must support at least the GET and HEAD methods. If you're handling CGI scripts, you should probably support the POST method too.
Four other methods (PUT, DELETE, OPTIONS, and TRACE) are defined in HTTP 1.1, but are rarely used. If a client requests a method you don't support, respond with "501 Not Implemented", like
HTTP/1.1 501 Not Implemented
[blank line here]
Return to Table of Contents
Supporting HTTP 1.0 Requests
To be compatible with older browsers, HTTP 1.1 servers must support HTTP 1.0 requests. In particular, when a request uses HTTP 1.0 (as identified in the initial request line),
don't require the Host: header, and
don't send the "100 Continue" response.
Return to Table of Contents
--------------------------------------------------------------------------------
The HTTP Specification
If you plan to do anything elaborate in HTTP, read the official specification. HTTP 1.0 was never made an official Internet standard, but the de facto standard is described in RFC 1945. HTTP 1.1 was developed by a working group of the IETF, openly gathering input from many sources before reaching an approximate consensus. The resulting specification is RFC 2616, released in June 1999.
These documents are available in various formats:
HTTP 1.0 (RFC 1945)-- HTML, text, and gzip'd PostScript
HTTP 1.1 (RFC 2616)-- HTML, text, PostScript, and PDF.
Download and print the version you'll be using, for reference and bedtime reading.
The World Wide Web Consortium has a page devoted to HTTP including news and updates, and a page listing HTTP specifications, drafts, and reports.
Other RFC's you might find useful:
RFC 822-- structure of Internet text messages, including header fields
RFC 2396-- definition of URL/URI syntax (replaces RFC 1738 and RFC 1808)
RFC 1521-- definition of MIME and of MIME types
Return to Table of Contents
--------------------------------------------------------------------------------
© 1997 James Marshall (comments welcome)
Last (significantly) modified: August 15, 1997 http://www.jmarshall.com/easy/http/
Sunday, 20 May 2007
bat文件的基本应用
bat是dos下的批处理文件
.cmd是nt内核命令行环境的另一种批处理文件
从更广义的角度来看,unix的shell脚本以及其它操作系统甚至应用程序中由外壳进行解释执行的文本,都具有与批处理文件十分相似的作用,而且同样是由专用解释器以行为单位解释执行,这种文本形式更通用的称谓是脚本语言。所以从某个程度分析,batch, unix shell, awk, basic, perl 等脚本语言都是一样的,只不过应用的范围和解释的平台各有不同而已。甚至有些应用程序仍然沿用批处理这一称呼,而其内容和扩展名与dos的批处理却又完全不同。
===================================
首先批处理文件是一个文本文件,这个文件的每一行都是一条DOS命令(大部分时候就好象我们在DOS提示符下执行的命令行一样),你可以使用DOS下的Edit或者Windows的记事本(notepad)等任何文本文件编辑工具创建和修改批处理文件。
==== 注 ===================
批处理文件中完全可以使用非dos命令,甚至可以使用不具有可执行特性的普通数据性文件,这缘于windows系统这个新型解释平台的涉入,使得批处理的应用越来越"边缘化"。所以我们讨论的批处理应该限定在dos环境或者命令行环境中,否则很多观念和设定都需要做比较大的变动。
========================
其次,批处理文件是一种简单的程序,可以通过条件语句(if)和流程控制语句(goto)来控制命令运行的流程,在批处理中也可以使用循环语句(for)来循环执行一条命令。当然,批处理文件的编程能力与C语言等编程语句比起来是十分有限的,也是十分不规范的。批处理的程序语句就是一条条的DOS命令(包括内部命令和外部命令),而批处理的能力主要取决于你所使用的命令。
==== 注 ==================
批处理文件(batch file)也可以称之为批处理程序(batch program),这一点与编译型语言有所不同,就c语言来说,扩展名为c或者cpp的文件可以称之为c语言文件或者c语言源代码,但只有编译连接后的exe文件才可以称之为c语言程序。因为批处理文件本身既具有文本的可读性,又具有程序的可执行性,这些称谓的界限是比较模糊的。
===========================
第三,每个编写好的批处理文件都相当于一个DOS的外部命令,你可以把它所在的目录放到你的DOS搜索路径(path)中来使得它可以在任意位置运行。一个良好的习惯是在硬盘上建立一个bat或者batch目录(例如C:\BATCH),然后将所有你编写的批处理文件放到该目录中,这样只要在path中设置上c:\batch,你就可以在任意位置运行所有你编写的批处理程序。
==== 注 =====
纯以dos系统而言,可执行程序大约可以细分为五类,依照执行优先级由高到低排列分别是:DOSKEY宏命令(预先驻留内存),COMMAND.COM中的内部命令(根据内存的环境随时进驻内存),以com为扩展名的可执行程序(由command.com 直接载入内存),以exe位扩展名的可执行程序(由command.com 重定位后载入内存),以bat位扩展名的批处理程序(由command.com 解释分析,根据其内容按优先级顺序调用第2,3,4,5种可执行程序,分析一行,执行一行,文件本身不载入内存)
============
第四,在DOS和Win9x/Me系统下,C:盘根目录下的AUTOEXEC.BAT批处理文件是自动运行批处理文件,每次系统启动时会自动运行该文件,你可以将系统每次启动时都要运行的命令放入该文件中,例如设置搜索路径,调入鼠标驱动和磁盘缓存,设置系统环境变量等。下面是一个运行于Windows 98下的autoexec.bat的示例:
@ECHO OFF
PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\UCDOS;C:\DOSTools;
C:\SYSTOOLS;C:\WINTOOLS;C:\BATCH
LH SMARTDRV.EXE /X
LH DOSKEY.COM /insert
LH CTMOUSE.EXE
SET TEMP=D:\TEMP
SET TMP=D:\TEMP
==== 注 =====
AUTOEXEC.BAT为DOS系统的自动运行批处理文件,由COMMAND.COM启动时解释执行;
而在Win9x环境中,不仅增加支持了 DOSSTART.BAT, WINSTART.BAT 等许多其它自动运行的批处理文件,对AUTOEXEC.BAT 也增加了 .DOS .W40 .BAK .OLD .PWS 等许多变体以适应复杂的环境和多变的需求。
==== willsort 编注 =============
以下关于命令的分类,有很多值得推敲的地方。常用命令中的@本不是命令,而dir、copy等也很常用的命令却没有列入, 而特殊命令中所有命令对我来说都是常用命令。建议将批处理所引用的命令分为内部命令、外部命令、第三方程序三类。而内部命令和外部命令中别有一类是专用于或常用于批处理中的命令可称之为"批处理命令"。
以下摘录MS-DOS 6.22 帮助文档中关于"批处理命令"的文字,当然,其中有些概念和定义已经有些落后了。
批处理命令
批处理文件或批处理程序是一个包含若干MS-DOS命令的正文文件,扩展名为.BAT。当在命令提示符下敲入批处理程序的名称时,MS-DOS成组执行此批处理程序中的命令。
任何在命令提示符下可使用的命令都可用在批处理程序中。此外,下面MS-DOS命令是专门在批处理程序中使用的。
==========
常用命令
echo、@、call、pause、rem(小技巧:用::代替rem)是批处理文件最常用的几个命令,我们就从他们开始学起。
==== 注 ===========
首先, @ 不是一个命令, 而是DOS 批处理的一个特殊标记符, 仅用于屏蔽命令行回显. 下面是DOS命令行或批处理中可能会见到的一些特殊标记符:
CR(0D) 命令行结束符
Escape(1B) ANSI转义字符引导符
Space(20) 常用的参数界定符
Tab(09) ; = 不常用的参数界定符
+ COPY命令文件连接符
* ? 文件通配符
"" 字符串界定符
| 命令管道符
< > >> 文件重定向符
@ 命令行回显屏蔽符
/ 参数开关引导符
: 批处理标签引导符
% 批处理变量引导符
其次, :: 确实可以起到rem 的注释作用, 而且更简洁有效; 但有两点需要注意:
第一, 除了 :: 之外, 任何以 :开头的字符行, 在批处理中都被视作标号, 而直接忽略其后的所有内容, 只是为了与正常的标号相区别, 建议使用 goto 所无法识别的标号, 即在 :后紧跟一个非字母数字的一个特殊符号.
第二, 与rem 不同的是, ::后的字符行在执行时不会回显, 无论是否用echo on打开命令行回显状态, 因为命令解释器不认为他是一个有效的命令行, 就此点来看, rem 在某些场合下将比 :: 更为适用; 另外, rem 可以用于 config.sys 文件中.
=====================
echo 表示显示此命令后的字符
echo off 表示在此语句后所有运行的命令都不显示命令行本身
@与echo off相象,但它是加在每个命令行的最前面,表示运行时不显示这一行的命令行(只能影响当前行)。
call 调用另一个批处理文件(如果不用call而直接调用别的批处理文件,那么执行完那个批处理文件后将无法返回当前文件并执行当前文件的后续命令)。
pause 运行此句会暂停批处理的执行并在屏幕上显示Press any key to continue...的提示,等待用户按任意键后继续
rem 表示此命令后的字符为解释行(注释),不执行,只是给自己今后参考用的(相当于程序中的注释)。
==== 注 =====
此处的描述较为混乱, 不如直接引用个命令的命令行帮助更为条理
-------------------------
ECHO
当程序运行时,显示或隐藏批处理程序中的正文。也可用于允许或禁止命令的回显。
在运行批处理程序时,MS-DOS一般在屏幕上显示(回显)批处理程序中的命令。
使用ECHO命令可关闭此功能。
语法
ECHO [ON|OFF]
若要用echo命令显示一条命令,可用下述语法:
echo [message]
参数
ON|OFF
指定是否允许命令的回显。若要显示当前的ECHO的设置,可使用不带参数的ECHO
命令。
message
指定让MS-DOS在屏幕上显示的正文。
-------------------
CALL
从一个批处理程序中调用另一个批处理程序,而不会引起第一个批处理的中止。
语法
CALL [drive:][path]filename [batch-parameters]
参数
[drive:][path]filename
指定要调用的批处理程序的名字及其存放处。文件名必须用.BAT作扩展名。
batch-parameters
指定批处理程序所需的命令行信息。
-------------------------------
PAUSE
暂停批处理程序的执行并显示一条消息,提示用户按任意键继续执行。只能在批处
理程序中使用该命令。
语法
PAUSE
REM
在批处理文件或CONFIG.SYS中加入注解。也可用REM命令来屏蔽命令(在CONFIG.SYS
中也可以用分号 ; 代替REM命令,但在批处理文件中则不能替代)。
语法
REM [string]
参数
string
指定要屏蔽的命令或要包含的注解。
=======================
例1:用edit编辑a.bat文件,输入下列内容后存盘为c:\a.bat,执行该批处理文件后可实现:将根目录中所有文件写入 a.txt中,启动UCDOS,进入WPS等功能。
批处理文件的内容为: 命令注释:
@echo off 不显示后续命令行及当前命令行
dir c:\*.* >a.txt 将c盘文件列表写入a.txt
call c:\ucdos\ucdos.bat 调用ucdos
echo 你好 显示"你好"
pause 暂停,等待按键继续
rem 准备运行wps 注释:准备运行wps
cd ucdos 进入ucdos目录
wps 运行wps
批处理文件的参数
批处理文件还可以像C语言的函数一样使用参数(相当于DOS命令的命令行参数),这需要用到一个参数表示符"%"。
%[1-9]表示参数,参数是指在运行批处理文件时在文件名后加的以空格(或者Tab)分隔的字符串。变量可以从%0到%9,%0表示批处理命令本身,其它参数字符串用%1到%9顺序表示。
例2:C:根目录下有一批处理文件名为f.bat,内容为:
@echo off
format %1
如果执行C:\>f a:
那么在执行f.bat时,%1就表示a:,这样format %1就相当于format a:,于是上面的命令运行时实际执行的是format a:
例3:C:根目录下一批处理文件名为t.bat,内容为:
@echo off
type %1
type %2
那么运行C:\>t a.txt b.txt
%1 : 表示a.txt
%2 : 表示b.txt
于是上面的命令将顺序地显示a.txt和b.txt文件的内容。
==== 注 ===============
参数在批处理中也作为变量处理, 所以同样使用百分号作为引导符, 其后跟0-9中的一个数字构成参数引用符. 引用符和参数之间 (例如上文中的 %1 与 a: ) 的关系类似于变量指针与变量值的关系. 当我们要引用第十一个或更多个参数时, 就必须移动DOS 的参数起始指针. shift 命令正充当了这个移动指针的角色, 它将参数的起始指针移动到下一个参数, 类似C 语言中的指针操作. 图示如下:
初始状态, cmd 为命令名, 可以用 %0 引用
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8 %9
经过1次shift后, cmd 将无法被引用
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8 %9
经过2次shift后, arg1也被废弃, %9指向为空, 没有引用意义
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8
遗憾的是, win9x 和DOS下均不支持 shift 的逆操作. 只有在 nt 内核命令行环境下, shift 才支持 /n 参数, 可以以第一参数为基准返复移动起始指针.
=================
特殊命令
if goto choice for是批处理文件中比较高级的命令,如果这几个你用得很熟练,你就是批处理文件的专家啦。
一、if 是条件语句,用来判断是否符合规定的条件,从而决定执行不同的命令。 有三种格式:
1、if [not] "参数" == "字符串" 待执行的命令
参数如果等于(not表示不等,下同)指定的字符串,则条件成立,运行命令,否则运行下一句。
例:if "%1"=="a" format a:
====
if 的命令行帮助中关于此点的描述为:
IF [NOT] string1==string2 command
在此有以下几点需要注意:
1. 包含字符串的双引号不是语法所必须的, 而只是习惯上使用的一种"防空"字符
2. string1 未必是参数, 它也可以是环境变量, 循环变量以及其他字符串常量或变量
3. command 不是语法所必须的, string2 后跟一个空格就可以构成一个有效的命令行
=============================
2、if [not] exist [路径\]文件名 待执行的命令
如果有指定的文件,则条件成立,运行命令,否则运行下一句。
如: if exist c:\config.sys type c:\config.sys
表示如果存在c:\config.sys文件,则显示它的内容。
****** 注 ********
也可以使用以下的用法:
if exist command
device 是指DOS系统中已加载的设备, 在win98下通常有:
AUX, PRN, CON, NUL
COM1, COM2, COM3, COM4
LPT1, LPT2, LPT3, LPT4
XMSXXXX0, EMMXXXX0
A: B: C: ...,
CLOCK$, CONFIG$, DblBuff$, IFS$HLP$
具体的内容会因硬软件环境的不同而略有差异, 使用这些设备名称时, 需要保证以下三点:
1. 该设备确实存在(由软件虚拟的设备除外)
2. 该设备驱动程序已加载(aux, prn等标准设备由系统缺省定义)
3. 该设备已准备好(主要是指a: b: ..., com1..., lpt1...等)
可通过命令 mem/d | find "device" /i 来检阅你的系统中所加载的设备
另外, 在DOS系统中, 设备也被认为是一种特殊的文件, 而文件也可以称作字符设备; 因为设备(device)与文件都是使用句柄(handle)来管理的, 句柄就是名字, 类似于文件名, 只不过句柄不是应用于磁盘管理, 而是应用于内存管理而已, 所谓设备加载也即指在内存中为其分配可引用的句柄.
==================================
3、if errorlevel <数字> 待执行的命令
很多DOS程序在运行结束后会返回一个数字值用来表示程序运行的结果(或者状态),通过if errorlevel命令可以判断程序的返回值,根据不同的返回值来决定执行不同的命令(返回值必须按照从大到小的顺序排列)。如果返回值等于指定的数字,则条件成立,运行命令,否则运行下一句。
如if errorlevel 2 goto x2
==== 注 ===========
返回值从大到小的顺序排列不是必须的, 而只是执行命令为 goto 时的习惯用法, 当使用 set 作为执行命令时, 通常会从小到大顺序排列, 比如需将返回码置入环境变量, 就需使用以下的顺序形式:
if errorlevel 1 set el=1
if errorlevel 2 set el=2
if errorlevel 3 set el=3
if errorlevel 4 set el=4
if errorlevel 5 set el=5
...
当然, 也可以使用以下循环来替代, 原理是一致的:
for %%e in (1 2 3 4 5 6 7 8...) do if errorlevel %%e set el=%%e
更高Ъ蚪嗟挠梅? 可以参考我写的另一篇关于获取 errorlevel 的文章
出现此种现象的原因是, if errorlevel 比较返回码的判断条件并非等于, 而是大于等于. 由于 goto 的跳转特性, 由小到大排序会导致在较小的返回码处就跳出; 而由于 set命令的 "重复" 赋值特性, 由大到小排序会导致较小的返回码 "覆盖" 较大的返回码.
另外, 虽然 if errorlevel=<数字> command 也是有效的命令行, 但也只是 command.com 解释命令行时将 = 作为命令行切分符而忽略掉罢了
===========================
二、goto 批处理文件运行到这里将跳到goto所指定的标号(标号即label,标号用:后跟标准字符串来定义)处,goto语句一般与if配合使用,根据不同的条件来执行不同的命令组。
如:
goto end
:end
echo this is the end
标号用":字符串"来定义,标号所在行不被执行。
==== willsort 编注
label 常被译为 "标签" , 但是这并不具有广泛的约定性.
goto 与 : 联用可实现执行中途的跳转, 再结合 if 可实现执行过程的条件分支, 多个 if 即可实现命令的分组, 类似 C 中 switch case 结构或者 Basic 中的 select case 结构, 大规模且结构化的命令分组即可实现高级语言中的函数功能. 以下是批处理和C/Basic在语法结构上的对照:
Batch C / Basic
goto&: goto&:
goto&:&if if{}&else{} / if&elseif&endif
goto&:&if... switch&case / select case
goto&:&if&set&envar... function() / function(),sub()
==================================
三、choice 使用此命令可以让用户输入一个字符(用于选择),从而根据用户的选择返回不同的errorlevel,然后于if errorlevel配合,根据用户的选择运行不同的命令。
注意:choice命令为DOS或者Windows系统提供的外部命令,不同版本的choice命令语法会稍有不同,请用choice /?查看用法。
choice的命令语法(该语法为Windows 2003中choice命令的语法,其它版本的choice的命令语法与此大同小异):
CHOICE [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text]
描述:
该工具允许用户从选择列表选择一个项目并返回所选项目的索引。
参数列表:
/C choices 指定要创建的选项列表。默认列表是 "YN"。
/N 在提示符中隐藏选项列表。提示前面的消息得到显示,
选项依旧处于启用状态。
/CS 允许选择分大小写的选项。在默认情况下,这个工具
是不分大小写的。
/T timeout 做出默认选择之前,暂停的秒数。可接受的值是从 0
到 9999。如果指定了 0,就不会有暂停,默认选项
会得到选择。
/D choice 在 nnnn 秒之后指定默认选项。字符必须在用 /C 选
项指定的一组选择中; 同时,必须用 /T 指定 nnnn。
/M text 指定提示之前要显示的消息。如果没有指定,工具只
显示提示。
/? 显示帮助消息。
注意:
ERRORLEVEL 环境变量被设置为从选择集选择的键索引。列出的第一个选
择返回 1,第二个选择返回 2,等等。如果用户按的键不是有效的选择,
该工具会发出警告响声。如果该工具检测到错误状态,它会返回 255 的
ERRORLEVEL 值。如果用户按 Ctrl+Break 或 Ctrl+C 键,该工具会返回 0
的 ERRORLEVEL 值。在一个批程序中使用 ERRORLEVEL 参数时,将参数降
序排列。
示例:
CHOICE /?
CHOICE /C YNC /M "确认请按 Y,否请按 N,或者取消请按 C。"
CHOICE /T 10 /C ync /CS /D y
CHOICE /C ab /M "选项 1 请选择 a,选项 2 请选择 b。"
CHOICE /C ab /N /M "选项 1 请选择 a,选项 2 请选择 b。"
==== willsort 编注 ===============================
我列出win98下choice的用法帮助, 已资区分
Waits for the user to choose one of a set of choices.
等待用户选择一组待选字符中的一个
CHOICE [/C[:]choices] [/N] [/S] [/T[:]c,nn] [text]
/C[:]choices Specifies allowable keys. Default is YN
指定允许的按键(待选字符), 默认为YN
/N Do not display choices and ? at end of prompt string.
不显示提示字符串中的问号和待选字符
/S Treat choice keys as case sensitive.
处理待选字符时大小写敏感
/T[:]c,nn Default choice to c after nn seconds
在 nn 秒后默认选择 c
text Prompt string to display
要显示的提示字符串
ERRORLEVEL is set to offset of key user presses in choices.
ERRORLEVEL 被设置为用户键入的字符在待选字符中的偏移值
如果我运行命令:CHOICE /C YNC /M "确认请按 Y,否请按 N,或者取消请按 C。"
屏幕上会显示:
确认请按 Y,否请按 N,或者取消请按 C。 [Y,N,C]?
例:test.bat的内容如下(注意,用if errorlevel判断返回值时,要按返回值从高到低排列):
@echo off
choice /C dme /M "defrag,mem,end"
if errorlevel 3 goto end
if errorlevel 2 goto mem
if errorlevel 1 goto defrag
:defrag
c:\dos\defrag
goto end
:mem
mem
goto end
:end
echo good bye
此批处理运行后,将显示"defrag,mem,end[D,M,E]?" ,用户可选择d m e ,然后if语句根据用户的选择作出判断,d表示执行标号为defrag的程序段,m表示执行标号为mem的程序段,e表示执行标号为end的程序段,每个程序段最后都以goto end将程序跳到end标号处,然后程序将显示good bye,批处理运行结束。
四、for 循环命令,只要条件符合,它将多次执行同一命令。
语法:
对一组文件中的每一个文件执行某个特定命令。
FOR %%variable IN (set) DO command [command-parameters]
%%variable 指定一个单一字母可替换的参数。
(set) 指定一个或一组文件。可以使用通配符。
command 指定对每个文件执行的命令。
command-parameters
为特定命令指定参数或命令行开关。
例如一个批处理文件中有一行:
for %%c in (*.bat *.txt) do type %%c
则该命令行会显示当前目录下所有以bat和txt为扩展名的文件的内容。
==== willsort 编注 =====================================================
需要指出的是, 当()中的字符串并非单个或多个文件名时, 它将单纯被当作字符串替换, 这个特性再加上()中可以嵌入多个字符串的特性, 很明显 for 可以被看作一种遍历型循环.
当然, 在 nt/2000/xp/2003 系列的命令行环境中, for 被赋予了更多的特性, 使之可以分析命令输出或者文件中的字符串, 也有很多开关被用于扩展了文件替换功能.
========================================================================
批处理示例
1. IF-EXIST
1) 首先用记事本在C:\建立一个test1.bat批处理文件,文件内容如下:
@echo off
IF EXIST \AUTOEXEC.BAT TYPE \AUTOEXEC.BAT
IF NOT EXIST \AUTOEXEC.BAT ECHO \AUTOEXEC.BAT does not exist
然后运行它:
C:\>TEST1.BAT
如果C:\存在AUTOEXEC.BAT文件,那么它的内容就会被显示出来,如果不存在,批处理就会提示你该文件不存在。
2) 接着再建立一个test2.bat文件,内容如下:
@ECHO OFF
IF EXIST \%1 TYPE \%1
IF NOT EXIST \%1 ECHO \%1 does not exist
执行:
C:\>TEST2 AUTOEXEC.BAT
该命令运行结果同上。
说明:
(1) IF EXIST 是用来测试文件是否存在的,格式为
IF EXIST [路径+文件名] 命令
(2) test2.bat文件中的%1是参数,DOS允许传递9个批参数信息给批处理文件,分别为%1~%9(%0表示test2命令本身) ,这有点象编程中的实参和形参的关系,%1是形参,AUTOEXEC.BAT是实参。
==== willsort 编注 =====================================================
DOS没有 "允许传递9个批参数信息" 的限制, 参数的个数只会受到命令行长度和所调用命令处理能力的限制. 但是, 我们在批处理程序中, 在同一时刻只能同时引用10个参数, 因为 DOS只给出了 %0~%9这十个参数引用符.
========================================================================
3) 更进一步的,建立一个名为TEST3.BAT的文件,内容如下:
@echo off
IF "%1" == "A" ECHO XIAO
IF "%2" == "B" ECHO TIAN
IF "%3" == "C" ECHO XIN
如果运行:
C:\>TEST3 A B C
屏幕上会显示:
XIAO
TIAN
XIN
如果运行:
C:\>TEST3 A B
屏幕上会显示
XIAO
TIAN
在这个命令执行过程中,DOS会将一个空字符串指定给参数%3。
2、IF-ERRORLEVEL
建立TEST4.BAT,内容如下:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 1 ECHO 文件拷贝失败
IF ERRORLEVEL 0 ECHO 成功拷贝文件
然后执行文件:
C:\>TEST4
如果文件拷贝成功,屏幕就会显示"成功拷贝文件",否则就会显示"文件拷贝失败"。
IF ERRORLEVEL 是用来测试它的上一个DOS命令的返回值的,注意只是上一个命令的返回值,而且返回值必须依照从大到小次序顺序判断。
因此下面的批处理文件是错误的:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 0 ECHO 成功拷贝文件
IF ERRORLEVEL 1 ECHO 未找到拷贝文件
IF ERRORLEVEL 2 ECHO 用户通过ctrl-c中止拷贝操作
IF ERRORLEVEL 3 ECHO 预置错误阻止文件拷贝操作
IF ERRORLEVEL 4 ECHO 拷贝过程中写盘错误
无论拷贝是否成功,后面的:
未找到拷贝文件
用户通过ctrl-c中止拷贝操作
预置错误阻止文件拷贝操作
拷贝过程中写盘错误
都将显示出来。
以下就是几个常用命令的返回值及其代表的意义:
backup
0 备份成功
1 未找到备份文件
2 文件共享冲突阻止备份完成
3 用户用ctrl-c中止备份
4 由于致命的错误使备份操作中止
diskcomp
0 盘比较相同
1 盘比较不同
2 用户通过ctrl-c中止比较操作
3 由于致命的错误使比较操作中止
4 预置错误中止比较
diskcopy
0 盘拷贝操作成功
1 非致命盘读/写错
2 用户通过ctrl-c结束拷贝操作
3 因致命的处理错误使盘拷贝中止
4 预置错误阻止拷贝操作
format
0 格式化成功
3 用户
.cmd是nt内核命令行环境的另一种批处理文件
从更广义的角度来看,unix的shell脚本以及其它操作系统甚至应用程序中由外壳进行解释执行的文本,都具有与批处理文件十分相似的作用,而且同样是由专用解释器以行为单位解释执行,这种文本形式更通用的称谓是脚本语言。所以从某个程度分析,batch, unix shell, awk, basic, perl 等脚本语言都是一样的,只不过应用的范围和解释的平台各有不同而已。甚至有些应用程序仍然沿用批处理这一称呼,而其内容和扩展名与dos的批处理却又完全不同。
===================================
首先批处理文件是一个文本文件,这个文件的每一行都是一条DOS命令(大部分时候就好象我们在DOS提示符下执行的命令行一样),你可以使用DOS下的Edit或者Windows的记事本(notepad)等任何文本文件编辑工具创建和修改批处理文件。
==== 注 ===================
批处理文件中完全可以使用非dos命令,甚至可以使用不具有可执行特性的普通数据性文件,这缘于windows系统这个新型解释平台的涉入,使得批处理的应用越来越"边缘化"。所以我们讨论的批处理应该限定在dos环境或者命令行环境中,否则很多观念和设定都需要做比较大的变动。
========================
其次,批处理文件是一种简单的程序,可以通过条件语句(if)和流程控制语句(goto)来控制命令运行的流程,在批处理中也可以使用循环语句(for)来循环执行一条命令。当然,批处理文件的编程能力与C语言等编程语句比起来是十分有限的,也是十分不规范的。批处理的程序语句就是一条条的DOS命令(包括内部命令和外部命令),而批处理的能力主要取决于你所使用的命令。
==== 注 ==================
批处理文件(batch file)也可以称之为批处理程序(batch program),这一点与编译型语言有所不同,就c语言来说,扩展名为c或者cpp的文件可以称之为c语言文件或者c语言源代码,但只有编译连接后的exe文件才可以称之为c语言程序。因为批处理文件本身既具有文本的可读性,又具有程序的可执行性,这些称谓的界限是比较模糊的。
===========================
第三,每个编写好的批处理文件都相当于一个DOS的外部命令,你可以把它所在的目录放到你的DOS搜索路径(path)中来使得它可以在任意位置运行。一个良好的习惯是在硬盘上建立一个bat或者batch目录(例如C:\BATCH),然后将所有你编写的批处理文件放到该目录中,这样只要在path中设置上c:\batch,你就可以在任意位置运行所有你编写的批处理程序。
==== 注 =====
纯以dos系统而言,可执行程序大约可以细分为五类,依照执行优先级由高到低排列分别是:DOSKEY宏命令(预先驻留内存),COMMAND.COM中的内部命令(根据内存的环境随时进驻内存),以com为扩展名的可执行程序(由command.com 直接载入内存),以exe位扩展名的可执行程序(由command.com 重定位后载入内存),以bat位扩展名的批处理程序(由command.com 解释分析,根据其内容按优先级顺序调用第2,3,4,5种可执行程序,分析一行,执行一行,文件本身不载入内存)
============
第四,在DOS和Win9x/Me系统下,C:盘根目录下的AUTOEXEC.BAT批处理文件是自动运行批处理文件,每次系统启动时会自动运行该文件,你可以将系统每次启动时都要运行的命令放入该文件中,例如设置搜索路径,调入鼠标驱动和磁盘缓存,设置系统环境变量等。下面是一个运行于Windows 98下的autoexec.bat的示例:
@ECHO OFF
PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\UCDOS;C:\DOSTools;
C:\SYSTOOLS;C:\WINTOOLS;C:\BATCH
LH SMARTDRV.EXE /X
LH DOSKEY.COM /insert
LH CTMOUSE.EXE
SET TEMP=D:\TEMP
SET TMP=D:\TEMP
==== 注 =====
AUTOEXEC.BAT为DOS系统的自动运行批处理文件,由COMMAND.COM启动时解释执行;
而在Win9x环境中,不仅增加支持了 DOSSTART.BAT, WINSTART.BAT 等许多其它自动运行的批处理文件,对AUTOEXEC.BAT 也增加了 .DOS .W40 .BAK .OLD .PWS 等许多变体以适应复杂的环境和多变的需求。
==== willsort 编注 =============
以下关于命令的分类,有很多值得推敲的地方。常用命令中的@本不是命令,而dir、copy等也很常用的命令却没有列入, 而特殊命令中所有命令对我来说都是常用命令。建议将批处理所引用的命令分为内部命令、外部命令、第三方程序三类。而内部命令和外部命令中别有一类是专用于或常用于批处理中的命令可称之为"批处理命令"。
以下摘录MS-DOS 6.22 帮助文档中关于"批处理命令"的文字,当然,其中有些概念和定义已经有些落后了。
批处理命令
批处理文件或批处理程序是一个包含若干MS-DOS命令的正文文件,扩展名为.BAT。当在命令提示符下敲入批处理程序的名称时,MS-DOS成组执行此批处理程序中的命令。
任何在命令提示符下可使用的命令都可用在批处理程序中。此外,下面MS-DOS命令是专门在批处理程序中使用的。
==========
常用命令
echo、@、call、pause、rem(小技巧:用::代替rem)是批处理文件最常用的几个命令,我们就从他们开始学起。
==== 注 ===========
首先, @ 不是一个命令, 而是DOS 批处理的一个特殊标记符, 仅用于屏蔽命令行回显. 下面是DOS命令行或批处理中可能会见到的一些特殊标记符:
CR(0D) 命令行结束符
Escape(1B) ANSI转义字符引导符
Space(20) 常用的参数界定符
Tab(09) ; = 不常用的参数界定符
+ COPY命令文件连接符
* ? 文件通配符
"" 字符串界定符
| 命令管道符
< > >> 文件重定向符
@ 命令行回显屏蔽符
/ 参数开关引导符
: 批处理标签引导符
% 批处理变量引导符
其次, :: 确实可以起到rem 的注释作用, 而且更简洁有效; 但有两点需要注意:
第一, 除了 :: 之外, 任何以 :开头的字符行, 在批处理中都被视作标号, 而直接忽略其后的所有内容, 只是为了与正常的标号相区别, 建议使用 goto 所无法识别的标号, 即在 :后紧跟一个非字母数字的一个特殊符号.
第二, 与rem 不同的是, ::后的字符行在执行时不会回显, 无论是否用echo on打开命令行回显状态, 因为命令解释器不认为他是一个有效的命令行, 就此点来看, rem 在某些场合下将比 :: 更为适用; 另外, rem 可以用于 config.sys 文件中.
=====================
echo 表示显示此命令后的字符
echo off 表示在此语句后所有运行的命令都不显示命令行本身
@与echo off相象,但它是加在每个命令行的最前面,表示运行时不显示这一行的命令行(只能影响当前行)。
call 调用另一个批处理文件(如果不用call而直接调用别的批处理文件,那么执行完那个批处理文件后将无法返回当前文件并执行当前文件的后续命令)。
pause 运行此句会暂停批处理的执行并在屏幕上显示Press any key to continue...的提示,等待用户按任意键后继续
rem 表示此命令后的字符为解释行(注释),不执行,只是给自己今后参考用的(相当于程序中的注释)。
==== 注 =====
此处的描述较为混乱, 不如直接引用个命令的命令行帮助更为条理
-------------------------
ECHO
当程序运行时,显示或隐藏批处理程序中的正文。也可用于允许或禁止命令的回显。
在运行批处理程序时,MS-DOS一般在屏幕上显示(回显)批处理程序中的命令。
使用ECHO命令可关闭此功能。
语法
ECHO [ON|OFF]
若要用echo命令显示一条命令,可用下述语法:
echo [message]
参数
ON|OFF
指定是否允许命令的回显。若要显示当前的ECHO的设置,可使用不带参数的ECHO
命令。
message
指定让MS-DOS在屏幕上显示的正文。
-------------------
CALL
从一个批处理程序中调用另一个批处理程序,而不会引起第一个批处理的中止。
语法
CALL [drive:][path]filename [batch-parameters]
参数
[drive:][path]filename
指定要调用的批处理程序的名字及其存放处。文件名必须用.BAT作扩展名。
batch-parameters
指定批处理程序所需的命令行信息。
-------------------------------
PAUSE
暂停批处理程序的执行并显示一条消息,提示用户按任意键继续执行。只能在批处
理程序中使用该命令。
语法
PAUSE
REM
在批处理文件或CONFIG.SYS中加入注解。也可用REM命令来屏蔽命令(在CONFIG.SYS
中也可以用分号 ; 代替REM命令,但在批处理文件中则不能替代)。
语法
REM [string]
参数
string
指定要屏蔽的命令或要包含的注解。
=======================
例1:用edit编辑a.bat文件,输入下列内容后存盘为c:\a.bat,执行该批处理文件后可实现:将根目录中所有文件写入 a.txt中,启动UCDOS,进入WPS等功能。
批处理文件的内容为: 命令注释:
@echo off 不显示后续命令行及当前命令行
dir c:\*.* >a.txt 将c盘文件列表写入a.txt
call c:\ucdos\ucdos.bat 调用ucdos
echo 你好 显示"你好"
pause 暂停,等待按键继续
rem 准备运行wps 注释:准备运行wps
cd ucdos 进入ucdos目录
wps 运行wps
批处理文件的参数
批处理文件还可以像C语言的函数一样使用参数(相当于DOS命令的命令行参数),这需要用到一个参数表示符"%"。
%[1-9]表示参数,参数是指在运行批处理文件时在文件名后加的以空格(或者Tab)分隔的字符串。变量可以从%0到%9,%0表示批处理命令本身,其它参数字符串用%1到%9顺序表示。
例2:C:根目录下有一批处理文件名为f.bat,内容为:
@echo off
format %1
如果执行C:\>f a:
那么在执行f.bat时,%1就表示a:,这样format %1就相当于format a:,于是上面的命令运行时实际执行的是format a:
例3:C:根目录下一批处理文件名为t.bat,内容为:
@echo off
type %1
type %2
那么运行C:\>t a.txt b.txt
%1 : 表示a.txt
%2 : 表示b.txt
于是上面的命令将顺序地显示a.txt和b.txt文件的内容。
==== 注 ===============
参数在批处理中也作为变量处理, 所以同样使用百分号作为引导符, 其后跟0-9中的一个数字构成参数引用符. 引用符和参数之间 (例如上文中的 %1 与 a: ) 的关系类似于变量指针与变量值的关系. 当我们要引用第十一个或更多个参数时, 就必须移动DOS 的参数起始指针. shift 命令正充当了这个移动指针的角色, 它将参数的起始指针移动到下一个参数, 类似C 语言中的指针操作. 图示如下:
初始状态, cmd 为命令名, 可以用 %0 引用
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8 %9
经过1次shift后, cmd 将无法被引用
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8 %9
经过2次shift后, arg1也被废弃, %9指向为空, 没有引用意义
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8
遗憾的是, win9x 和DOS下均不支持 shift 的逆操作. 只有在 nt 内核命令行环境下, shift 才支持 /n 参数, 可以以第一参数为基准返复移动起始指针.
=================
特殊命令
if goto choice for是批处理文件中比较高级的命令,如果这几个你用得很熟练,你就是批处理文件的专家啦。
一、if 是条件语句,用来判断是否符合规定的条件,从而决定执行不同的命令。 有三种格式:
1、if [not] "参数" == "字符串" 待执行的命令
参数如果等于(not表示不等,下同)指定的字符串,则条件成立,运行命令,否则运行下一句。
例:if "%1"=="a" format a:
====
if 的命令行帮助中关于此点的描述为:
IF [NOT] string1==string2 command
在此有以下几点需要注意:
1. 包含字符串的双引号不是语法所必须的, 而只是习惯上使用的一种"防空"字符
2. string1 未必是参数, 它也可以是环境变量, 循环变量以及其他字符串常量或变量
3. command 不是语法所必须的, string2 后跟一个空格就可以构成一个有效的命令行
=============================
2、if [not] exist [路径\]文件名 待执行的命令
如果有指定的文件,则条件成立,运行命令,否则运行下一句。
如: if exist c:\config.sys type c:\config.sys
表示如果存在c:\config.sys文件,则显示它的内容。
****** 注 ********
也可以使用以下的用法:
if exist command
device 是指DOS系统中已加载的设备, 在win98下通常有:
AUX, PRN, CON, NUL
COM1, COM2, COM3, COM4
LPT1, LPT2, LPT3, LPT4
XMSXXXX0, EMMXXXX0
A: B: C: ...,
CLOCK$, CONFIG$, DblBuff$, IFS$HLP$
具体的内容会因硬软件环境的不同而略有差异, 使用这些设备名称时, 需要保证以下三点:
1. 该设备确实存在(由软件虚拟的设备除外)
2. 该设备驱动程序已加载(aux, prn等标准设备由系统缺省定义)
3. 该设备已准备好(主要是指a: b: ..., com1..., lpt1...等)
可通过命令 mem/d | find "device" /i 来检阅你的系统中所加载的设备
另外, 在DOS系统中, 设备也被认为是一种特殊的文件, 而文件也可以称作字符设备; 因为设备(device)与文件都是使用句柄(handle)来管理的, 句柄就是名字, 类似于文件名, 只不过句柄不是应用于磁盘管理, 而是应用于内存管理而已, 所谓设备加载也即指在内存中为其分配可引用的句柄.
==================================
3、if errorlevel <数字> 待执行的命令
很多DOS程序在运行结束后会返回一个数字值用来表示程序运行的结果(或者状态),通过if errorlevel命令可以判断程序的返回值,根据不同的返回值来决定执行不同的命令(返回值必须按照从大到小的顺序排列)。如果返回值等于指定的数字,则条件成立,运行命令,否则运行下一句。
如if errorlevel 2 goto x2
==== 注 ===========
返回值从大到小的顺序排列不是必须的, 而只是执行命令为 goto 时的习惯用法, 当使用 set 作为执行命令时, 通常会从小到大顺序排列, 比如需将返回码置入环境变量, 就需使用以下的顺序形式:
if errorlevel 1 set el=1
if errorlevel 2 set el=2
if errorlevel 3 set el=3
if errorlevel 4 set el=4
if errorlevel 5 set el=5
...
当然, 也可以使用以下循环来替代, 原理是一致的:
for %%e in (1 2 3 4 5 6 7 8...) do if errorlevel %%e set el=%%e
更高Ъ蚪嗟挠梅? 可以参考我写的另一篇关于获取 errorlevel 的文章
出现此种现象的原因是, if errorlevel 比较返回码的判断条件并非等于, 而是大于等于. 由于 goto 的跳转特性, 由小到大排序会导致在较小的返回码处就跳出; 而由于 set命令的 "重复" 赋值特性, 由大到小排序会导致较小的返回码 "覆盖" 较大的返回码.
另外, 虽然 if errorlevel=<数字> command 也是有效的命令行, 但也只是 command.com 解释命令行时将 = 作为命令行切分符而忽略掉罢了
===========================
二、goto 批处理文件运行到这里将跳到goto所指定的标号(标号即label,标号用:后跟标准字符串来定义)处,goto语句一般与if配合使用,根据不同的条件来执行不同的命令组。
如:
goto end
:end
echo this is the end
标号用":字符串"来定义,标号所在行不被执行。
==== willsort 编注
label 常被译为 "标签" , 但是这并不具有广泛的约定性.
goto 与 : 联用可实现执行中途的跳转, 再结合 if 可实现执行过程的条件分支, 多个 if 即可实现命令的分组, 类似 C 中 switch case 结构或者 Basic 中的 select case 结构, 大规模且结构化的命令分组即可实现高级语言中的函数功能. 以下是批处理和C/Basic在语法结构上的对照:
Batch C / Basic
goto&: goto&:
goto&:&if if{}&else{} / if&elseif&endif
goto&:&if... switch&case / select case
goto&:&if&set&envar... function() / function(),sub()
==================================
三、choice 使用此命令可以让用户输入一个字符(用于选择),从而根据用户的选择返回不同的errorlevel,然后于if errorlevel配合,根据用户的选择运行不同的命令。
注意:choice命令为DOS或者Windows系统提供的外部命令,不同版本的choice命令语法会稍有不同,请用choice /?查看用法。
choice的命令语法(该语法为Windows 2003中choice命令的语法,其它版本的choice的命令语法与此大同小异):
CHOICE [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text]
描述:
该工具允许用户从选择列表选择一个项目并返回所选项目的索引。
参数列表:
/C choices 指定要创建的选项列表。默认列表是 "YN"。
/N 在提示符中隐藏选项列表。提示前面的消息得到显示,
选项依旧处于启用状态。
/CS 允许选择分大小写的选项。在默认情况下,这个工具
是不分大小写的。
/T timeout 做出默认选择之前,暂停的秒数。可接受的值是从 0
到 9999。如果指定了 0,就不会有暂停,默认选项
会得到选择。
/D choice 在 nnnn 秒之后指定默认选项。字符必须在用 /C 选
项指定的一组选择中; 同时,必须用 /T 指定 nnnn。
/M text 指定提示之前要显示的消息。如果没有指定,工具只
显示提示。
/? 显示帮助消息。
注意:
ERRORLEVEL 环境变量被设置为从选择集选择的键索引。列出的第一个选
择返回 1,第二个选择返回 2,等等。如果用户按的键不是有效的选择,
该工具会发出警告响声。如果该工具检测到错误状态,它会返回 255 的
ERRORLEVEL 值。如果用户按 Ctrl+Break 或 Ctrl+C 键,该工具会返回 0
的 ERRORLEVEL 值。在一个批程序中使用 ERRORLEVEL 参数时,将参数降
序排列。
示例:
CHOICE /?
CHOICE /C YNC /M "确认请按 Y,否请按 N,或者取消请按 C。"
CHOICE /T 10 /C ync /CS /D y
CHOICE /C ab /M "选项 1 请选择 a,选项 2 请选择 b。"
CHOICE /C ab /N /M "选项 1 请选择 a,选项 2 请选择 b。"
==== willsort 编注 ===============================
我列出win98下choice的用法帮助, 已资区分
Waits for the user to choose one of a set of choices.
等待用户选择一组待选字符中的一个
CHOICE [/C[:]choices] [/N] [/S] [/T[:]c,nn] [text]
/C[:]choices Specifies allowable keys. Default is YN
指定允许的按键(待选字符), 默认为YN
/N Do not display choices and ? at end of prompt string.
不显示提示字符串中的问号和待选字符
/S Treat choice keys as case sensitive.
处理待选字符时大小写敏感
/T[:]c,nn Default choice to c after nn seconds
在 nn 秒后默认选择 c
text Prompt string to display
要显示的提示字符串
ERRORLEVEL is set to offset of key user presses in choices.
ERRORLEVEL 被设置为用户键入的字符在待选字符中的偏移值
如果我运行命令:CHOICE /C YNC /M "确认请按 Y,否请按 N,或者取消请按 C。"
屏幕上会显示:
确认请按 Y,否请按 N,或者取消请按 C。 [Y,N,C]?
例:test.bat的内容如下(注意,用if errorlevel判断返回值时,要按返回值从高到低排列):
@echo off
choice /C dme /M "defrag,mem,end"
if errorlevel 3 goto end
if errorlevel 2 goto mem
if errorlevel 1 goto defrag
:defrag
c:\dos\defrag
goto end
:mem
mem
goto end
:end
echo good bye
此批处理运行后,将显示"defrag,mem,end[D,M,E]?" ,用户可选择d m e ,然后if语句根据用户的选择作出判断,d表示执行标号为defrag的程序段,m表示执行标号为mem的程序段,e表示执行标号为end的程序段,每个程序段最后都以goto end将程序跳到end标号处,然后程序将显示good bye,批处理运行结束。
四、for 循环命令,只要条件符合,它将多次执行同一命令。
语法:
对一组文件中的每一个文件执行某个特定命令。
FOR %%variable IN (set) DO command [command-parameters]
%%variable 指定一个单一字母可替换的参数。
(set) 指定一个或一组文件。可以使用通配符。
command 指定对每个文件执行的命令。
command-parameters
为特定命令指定参数或命令行开关。
例如一个批处理文件中有一行:
for %%c in (*.bat *.txt) do type %%c
则该命令行会显示当前目录下所有以bat和txt为扩展名的文件的内容。
==== willsort 编注 =====================================================
需要指出的是, 当()中的字符串并非单个或多个文件名时, 它将单纯被当作字符串替换, 这个特性再加上()中可以嵌入多个字符串的特性, 很明显 for 可以被看作一种遍历型循环.
当然, 在 nt/2000/xp/2003 系列的命令行环境中, for 被赋予了更多的特性, 使之可以分析命令输出或者文件中的字符串, 也有很多开关被用于扩展了文件替换功能.
========================================================================
批处理示例
1. IF-EXIST
1) 首先用记事本在C:\建立一个test1.bat批处理文件,文件内容如下:
@echo off
IF EXIST \AUTOEXEC.BAT TYPE \AUTOEXEC.BAT
IF NOT EXIST \AUTOEXEC.BAT ECHO \AUTOEXEC.BAT does not exist
然后运行它:
C:\>TEST1.BAT
如果C:\存在AUTOEXEC.BAT文件,那么它的内容就会被显示出来,如果不存在,批处理就会提示你该文件不存在。
2) 接着再建立一个test2.bat文件,内容如下:
@ECHO OFF
IF EXIST \%1 TYPE \%1
IF NOT EXIST \%1 ECHO \%1 does not exist
执行:
C:\>TEST2 AUTOEXEC.BAT
该命令运行结果同上。
说明:
(1) IF EXIST 是用来测试文件是否存在的,格式为
IF EXIST [路径+文件名] 命令
(2) test2.bat文件中的%1是参数,DOS允许传递9个批参数信息给批处理文件,分别为%1~%9(%0表示test2命令本身) ,这有点象编程中的实参和形参的关系,%1是形参,AUTOEXEC.BAT是实参。
==== willsort 编注 =====================================================
DOS没有 "允许传递9个批参数信息" 的限制, 参数的个数只会受到命令行长度和所调用命令处理能力的限制. 但是, 我们在批处理程序中, 在同一时刻只能同时引用10个参数, 因为 DOS只给出了 %0~%9这十个参数引用符.
========================================================================
3) 更进一步的,建立一个名为TEST3.BAT的文件,内容如下:
@echo off
IF "%1" == "A" ECHO XIAO
IF "%2" == "B" ECHO TIAN
IF "%3" == "C" ECHO XIN
如果运行:
C:\>TEST3 A B C
屏幕上会显示:
XIAO
TIAN
XIN
如果运行:
C:\>TEST3 A B
屏幕上会显示
XIAO
TIAN
在这个命令执行过程中,DOS会将一个空字符串指定给参数%3。
2、IF-ERRORLEVEL
建立TEST4.BAT,内容如下:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 1 ECHO 文件拷贝失败
IF ERRORLEVEL 0 ECHO 成功拷贝文件
然后执行文件:
C:\>TEST4
如果文件拷贝成功,屏幕就会显示"成功拷贝文件",否则就会显示"文件拷贝失败"。
IF ERRORLEVEL 是用来测试它的上一个DOS命令的返回值的,注意只是上一个命令的返回值,而且返回值必须依照从大到小次序顺序判断。
因此下面的批处理文件是错误的:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 0 ECHO 成功拷贝文件
IF ERRORLEVEL 1 ECHO 未找到拷贝文件
IF ERRORLEVEL 2 ECHO 用户通过ctrl-c中止拷贝操作
IF ERRORLEVEL 3 ECHO 预置错误阻止文件拷贝操作
IF ERRORLEVEL 4 ECHO 拷贝过程中写盘错误
无论拷贝是否成功,后面的:
未找到拷贝文件
用户通过ctrl-c中止拷贝操作
预置错误阻止文件拷贝操作
拷贝过程中写盘错误
都将显示出来。
以下就是几个常用命令的返回值及其代表的意义:
backup
0 备份成功
1 未找到备份文件
2 文件共享冲突阻止备份完成
3 用户用ctrl-c中止备份
4 由于致命的错误使备份操作中止
diskcomp
0 盘比较相同
1 盘比较不同
2 用户通过ctrl-c中止比较操作
3 由于致命的错误使比较操作中止
4 预置错误中止比较
diskcopy
0 盘拷贝操作成功
1 非致命盘读/写错
2 用户通过ctrl-c结束拷贝操作
3 因致命的处理错误使盘拷贝中止
4 预置错误阻止拷贝操作
format
0 格式化成功
3 用户
Tuesday, 15 May 2007
Gladder
Thanks Maro for him to tell me a trick about using Firefox to access some sits such as wikipedia, BBC news and nearly all webs which considered with little political reason, so we are allowed to open.
this technology is call gladder which I had heard before. if I want to access site A, I can land site B, then load A as a part of source B. so, it is not easy for government to filter.
there are many such services like:
proxyhub.co.uk
anonymous.com
here we can use GLADDER in firefox as plug-in
download it from http://gneheix.googlepages.com/gladder
this technology is call gladder which I had heard before. if I want to access site A, I can land site B, then load A as a part of source B. so, it is not easy for government to filter.
there are many such services like:
proxyhub.co.uk
anonymous.com
here we can use GLADDER in firefox as plug-in
download it from http://gneheix.googlepages.com/gladder
Monday, 16 April 2007
google_doc
I am so happy to finish my job today to create all elements i will need later, including all posts post today and all labels.
In this process, I find a quite fine tool and have to admire how great google is, that is google doc&document, which means you can use word, excell, and so on online, compared to OFFICE, we need to instal and maintain them, however you do not need to worried about these, only to using it and save online, when we using OFFICE, one problem is that the font we using on this pc maybe not instal on that pc, your word and others will fail to appear. however, it does not happened again, because all google doc&document are using same standand. maybe it will completely take market, because it can implement nearly all functions which OFFICE have, and the speed is fast at least when I use in IT_room. The favor is that we can create pdf by this, which is OFFICE can not succee. I can write pdf, modify it and read it then save on google. quite funny.
welcome to using it:http://docs.google.com/
In this process, I find a quite fine tool and have to admire how great google is, that is google doc&document, which means you can use word, excell, and so on online, compared to OFFICE, we need to instal and maintain them, however you do not need to worried about these, only to using it and save online, when we using OFFICE, one problem is that the font we using on this pc maybe not instal on that pc, your word and others will fail to appear. however, it does not happened again, because all google doc&document are using same standand. maybe it will completely take market, because it can implement nearly all functions which OFFICE have, and the speed is fast at least when I use in IT_room. The favor is that we can create pdf by this, which is OFFICE can not succee. I can write pdf, modify it and read it then save on google. quite funny.
welcome to using it:http://docs.google.com/
说说blogger
Blogger是一个博客,现在属于google。 他非常适于构建自己的博客,也就是说可以通过写代码就可以完成几乎所有的事情,我之前向这么做,当然你也可以使用已经构建好的模板,就像我现在一样 。 他的设计模式和我现在学的java 很类似,其实现在很多东西也都在这样趋向。他本身提供一些特定的变量,也就是你可以在dashboard里面所作的动作,例如发贴,形式设定等,然后你可以通过写一个模板或用已有的模板,来利用它的这些变量达到你所想要得功能。但并不是所有变量你现在都已经接触到了,我们可以去blogger的help页面去查找几乎所有的变量.这就像java中提供了一个api,你可以通过使用它里面的东西组合成一大堆新的东西。也可以非常像是在实现并扩建一个接口。所以熟悉面向对象编程的高手来说应该不是一个问题。当然我之前没用过别的任何博客,所以也许别的也是这样,我却不知道。
我在这里说说我这几天捣鼓这个blogger的一些东西吧,因为期间我顺便学了一些html,css和javascript,之前,我所作的网页都是通过使用工具软件来做,所以很多低层次的东西我是完全不知道的。首先你要去弄这个blogger,有一个资源是非常有用的,也就是他的帮助文档,学java的时候大家都知道,他的帮助文档api是非常有用的。你可以在里面发现一些基本用法,当然还有低层次的东西,例如系统所使用的变量,这样你就可以通过使用这些变量来少做很多事情。然后还有一个很好的资源就是他的默认模板,随便选一个来分析一下,你就会发现一些共性的东西,如果你只是想简单的增加一些功能或更改布局,那就只需要在这些模板代码里面改几个数字或换几个链接。附件里的就是我分析的第一个模板template.html.
我的blogger是通过ftp发布的,因为由于政策的原因,中国是不能浏览这个页面,那他就来一个对策,通过ftp域名榜定,所以其实如果你有时间,你可以自己在本地构建好自己想要得网页,然后结合他的部分变量,然后上传到你的ftp上,那你就既可以让你的页面非常好看,功能非常强大,也可以使用blogger本身的一些功能。我就是我原来的初衷,但我学习上时间不太好安排,所以就算了。我的ftp提供是bloggerspaces,你可以去参阅一下他完整的教程。
在来说说他的内部,blogger是通过调用你的模板,结合自己数据库里面的数据来同步生成html和archieve文件,同时他使用了atom和css格式来规范你的信息。你可以通过察看你的ftp就知道了。在html中,他有一个indix.html,也就是首页,blogger在你每次修改或发新贴或有新的评论,也就是有改动的时候,系统都会对你的页面进行更改,archieve.html也是一样,每个贴为一个html页面,然后每个月的帖放在一个文件下,然后一年的帖放在一个文件目录下。最上层的,就是每天的archieve.html。此外,最上层还有一个atom.xml和css.xml文件,他们就是用来管理你的这些所有文件用的。我之前对html,xhtml,css,xml一无所知的,但花了一个下午的时间,来阅读一个网站,我就觉得其实网页编程的基础还不时很难,如果你只是想看懂网页代码的话,我觉得这个w3c网站还是很不错的。其实你还可以从上面学到别的很多东西,例如flash。里面的酷站欣赏也很不错,可是大多是都是用flash作的,公司商业嘛,可以理解。
最后在来说说模板,模版里面的东西其实也不多的,用到最多的无非就是两个东西,一个html语言,还有一个css语言,html语言实现的基础执行,css实现的是一个基本框架。所以你在css里面设计好页面由几部分组成,每一部分里面的字体,图片,填充等。然后再html语言里面放上我前面提到的系统提供的变量或别的一些你想要得东西。你去看看你就会觉得不难得,真的。我当初在search的时候,发现还有一个链接也听不错的, 你可以去看看。现在的模板所执行的标准其实也几乎都是一样的,他的标准是w3的标准。
我这里再提一个免费工具,可以提供另外一种连接显示方式,具体方法参看主页,说的已经很详细了。
关于blogger就先说到这里。
我在这里说说我这几天捣鼓这个blogger的一些东西吧,因为期间我顺便学了一些html,css和javascript,之前,我所作的网页都是通过使用工具软件来做,所以很多低层次的东西我是完全不知道的。首先你要去弄这个blogger,有一个资源是非常有用的,也就是他的帮助文档,学java的时候大家都知道,他的帮助文档api是非常有用的。你可以在里面发现一些基本用法,当然还有低层次的东西,例如系统所使用的变量,这样你就可以通过使用这些变量来少做很多事情。然后还有一个很好的资源就是他的默认模板,随便选一个来分析一下,你就会发现一些共性的东西,如果你只是想简单的增加一些功能或更改布局,那就只需要在这些模板代码里面改几个数字或换几个链接。附件里的就是我分析的第一个模板template.html.
我的blogger是通过ftp发布的,因为由于政策的原因,中国是不能浏览这个页面,那他就来一个对策,通过ftp域名榜定,所以其实如果你有时间,你可以自己在本地构建好自己想要得网页,然后结合他的部分变量,然后上传到你的ftp上,那你就既可以让你的页面非常好看,功能非常强大,也可以使用blogger本身的一些功能。我就是我原来的初衷,但我学习上时间不太好安排,所以就算了。我的ftp提供是bloggerspaces,你可以去参阅一下他完整的教程。
在来说说他的内部,blogger是通过调用你的模板,结合自己数据库里面的数据来同步生成html和archieve文件,同时他使用了atom和css格式来规范你的信息。你可以通过察看你的ftp就知道了。在html中,他有一个indix.html,也就是首页,blogger在你每次修改或发新贴或有新的评论,也就是有改动的时候,系统都会对你的页面进行更改,archieve.html也是一样,每个贴为一个html页面,然后每个月的帖放在一个文件下,然后一年的帖放在一个文件目录下。最上层的,就是每天的archieve.html。此外,最上层还有一个atom.xml和css.xml文件,他们就是用来管理你的这些所有文件用的。我之前对html,xhtml,css,xml一无所知的,但花了一个下午的时间,来阅读一个网站,我就觉得其实网页编程的基础还不时很难,如果你只是想看懂网页代码的话,我觉得这个w3c网站还是很不错的。其实你还可以从上面学到别的很多东西,例如flash。里面的酷站欣赏也很不错,可是大多是都是用flash作的,公司商业嘛,可以理解。
最后在来说说模板,模版里面的东西其实也不多的,用到最多的无非就是两个东西,一个html语言,还有一个css语言,html语言实现的基础执行,css实现的是一个基本框架。所以你在css里面设计好页面由几部分组成,每一部分里面的字体,图片,填充等。然后再html语言里面放上我前面提到的系统提供的变量或别的一些你想要得东西。你去看看你就会觉得不难得,真的。我当初在search的时候,发现还有一个链接也听不错的, 你可以去看看。现在的模板所执行的标准其实也几乎都是一样的,他的标准是w3的标准。
我这里再提一个免费工具,可以提供另外一种连接显示方式,具体方法参看主页,说的已经很详细了。
关于blogger就先说到这里。
Subscribe to:
Posts (Atom)