一、说明
http.Response是我们请求服务器之后得到的响应数据,结构如下:
type Response struct {
Status string
StatusCode int
Proto string
ProtoMajor int
ProtoMinor int
Header Header
Body io.ReadCloser
ContentLength int64
TransferEncoding []string
Close bool
Trailer Header
Request *Request
TLS *tls.ConnectionState
}
其中常用的属性说明如下:
- Status:响应状态,字符串,"200 OK"
- StatusCode:响应状态码,200、304、404等
- Proto:协议类型,字符串,"HTTP/1.1"
- ProtoMajor:协议的主版本号
- ProtoMinor:协议的副版本号
- Request:响应的请求信息
- TransferEncoding:传输编码
- ContentLength:响应数据包长度
- Header:响应头
- Body:响应的body信息
二、使用方法
package main
import (
"net/http"
"fmt"
"io/ioutil"
)
func main(){
rs, err := http.Get("http://baidu.com")
if err != nil{
fmt.Println(err)
return
}
//读取响应头信息
fmt.Println("rs.Status:", rs.Status)
fmt.Println("rs.StatusCode:", rs.StatusCode)
fmt.Println("rs.TransferEncoding:", rs.TransferEncoding)
fmt.Println("rs.Proto:", rs.Proto)
fmt.Println("rs.ProtoMajor:", rs.ProtoMajor)
fmt.Println("rs.ProtoMinor:", rs.ProtoMinor)
fmt.Println("rs.Request:", rs.Request)
fmt.Println("rs.ContentLength:", rs.ContentLength)
fmt.Println("rs.Header:", rs.Header)
fmt.Println("rs.Close:", rs.Close)
//读取body中的数据
fmt.Println()
body, err := ioutil.ReadAll(rs.Body)
defer rs.Body.Close()
fmt.Println(string(body))
}
输出:
rs.Status: 200 OK
rs.StatusCode: 200
rs.TransferEncoding: []
rs.Proto: HTTP/1.1
rs.ProtoMajor: 1
rs.ProtoMinor: 1
rs.Request: &{GET http://baidu.com HTTP/1.1 1 1 map[] <nil> <nil> 0 [] false baidu.com map[] map[] <nil> map[] <nil> <nil> <nil> <nil>}
rs.ContentLength: 81
rs.Header: map[Date:[Thu, 24 Aug 2017 14:02:58 GMT] Last-Modified:[Tue, 12 Jan 2010 13:48:00 GMT] Accept-Ranges:[bytes] Cache-Control:[max-age=86400] Connection:[Keep-Alive] Content-Type:[text/html] Server:[Apache] Etag:["51-47cf7e6ee8400"] Content-Length:[81] Expires:[Fri, 25 Aug 2017 14:02:58 GMT]]
rs.Close: false
<html>
<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
</html>
此处评论已关闭