Create 15.3.md

This commit is contained in:
glight2000
2015-12-11 14:38:44 +08:00
parent eeb2b6ee0a
commit 2009b88bb4

49
eBook/15.3.md Normal file
View File

@@ -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
```