From 2009b88bb436eb3dc5723bdb2c16f0d68c008adf Mon Sep 17 00:00:00 2001 From: glight2000 <173959153@qq.com> Date: Fri, 11 Dec 2015 14:38:44 +0800 Subject: [PATCH] Create 15.3.md --- eBook/15.3.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 eBook/15.3.md diff --git a/eBook/15.3.md b/eBook/15.3.md new file mode 100644 index 0000000..e4d2d67 --- /dev/null +++ b/eBook/15.3.md @@ -0,0 +1,49 @@ +# 15.3 访问并读取页面 + +在下边这个程序中,数组中的url都将被访问:会发送一个简单的`http.Head()`请求查看返回值;它的声明如下:`func Head(url string) (r *Response, err error)` + +返回状态码会被打印出来。 + +示例 15.7 [poll_url.go](examples/chapter_15/poll_url.go): +```go +package main + +import ( + "fmt" + "net/http" +) + +var urls = []string{ + "http://www.google.com/", + "http://golang.org/", + "http://blog.golang.org/", +} + +func main() { + // Execute an HTTP HEAD request for all url's + // and returns the HTTP status string or an error string. + for _, url := range urls { + resp, err := http.Head(url) + if err != nil { + fmt.Println("Error:", url, err) + } + fmt.Print(url, ": ", resp.Status) + } +} +``` +输出为: +``` +http://www.google.com/ : 302 Found +http://golang.org/ : 200 OK +http://blog.golang.org/ : 200 OK +``` +***译者注*** 由于国内的网络环境现状,很有可能见到如下超时错误提示: +``` +Error: http://www.google.com/ Head http://www.google.com/: dial tcp 216.58.221.100:80: connectex: A connection attempt failed because the connected pa +rty did not properly respond after a period of time, or established connection failed because connected host has failed to respond. +``` +在下边的程序中我们使用`http.Get()`获取网页内容; `Get`的返回值`res`中的`Body`属性包含了网页内容,然后我们用`ioutil.ReadAll`把它读出来: + +示例 15.8 [http_fetch.go](examples/chapter_15/http_fetch.go): +```go +```