• Go

Go HTTP Client

标准库中的net / http软件包提供了发出HTTP网络请求的功能。

在示例中,我们使用httpbin.org这是一个聪明的服务,可以返回特定的HTTP响应,这对于演示HTTP协议的各个方面很有用。

基本HTTP GET 为简单起见,此示例使用http.Get()。 在实际程序中应该使用具有超时的自定义客户端,如下所述。

uri := "https://httpbin.org/html"
resp, err := http.Get(uri)
if err != nil {
    log.Fatalf("http.Get() failed with '%s'\n", err)
}

// it's important to close resp.Body or else we'll leak network connection
// it must be done after checking for error because in error case
// resp.Body can be nil
defer resp.Body.Close()
d, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatalf("ioutil.ReadAll() failed with '%s'\n", err)
}

contentType := resp.Header.Get("Content-Type")
fmt.Printf("http.Get() returned content of type '%s' and size %d bytes.\nStatus code: %d\n", contentType, len(d), resp.StatusCode)

// getting page that doesn't exist return 404
uri = "https://httpbin.org/page-doesnt-exist"
resp, err = http.Get(uri)
if err != nil {
    log.Fatalf("http.Get() failed with '%s'\n", err)
}

contentType = resp.Header.Get("Content-Type")
fmt.Printf("\nhttp.Get() returned content of type '%s' and size %d bytes.\nStatus code: %d\n", contentType, len(d), resp.StatusCode)

// acessing non-existent host fails
uri = "http://website.not-exists.as/index.html"
resp, err = http.Get(uri)
if err != nil {
    fmt.Printf("\nhttp.Get() failed with: '%s'\nresp: %v\n", err, resp)
}

这显示了如何对URL发出HTTP GET请求(在这种情况下为HTML页面)。

我使用uri作为变量名,因为有net / url包,这意味着在同一文件中导入net / url时使用更自然的url会导致命名冲突。

如果没有错误,则http.Get()返回* http.Response,其中包含以下重要字段:

正文是包含响应内容的io.Reader。 如果URL是HTML页面,则为HTML数据。 如果网址是PNG图片,则为PNG数据 StatusCode是描述HTTP状态代码的int。 200表示确定。 404表示未找到等。 标头包含响应标头。 其类型为map [string] [] string,因为根据HTTP规范,可以使用多个具有相同名称的标头 如果没有错误返回,请务必使用resp.Body.Close(),否则将浪费资源。

尝试访问服务器上不存在的页面会返回状态码为404(未找到)的响应。

尝试访问不存在的主机将失败,在这种情况下,响应为nil。

HTTP GET using custom client http.Get()只是委派所有工作http.DefaultClient的包装,后者是* http.Client类型的包变量。

最好不要使用http.Get,因为默认客户端没有超时,这意味着它将永远等待连接到速度慢,错误的服务器或恶意服务器。

client := &http.Client{}
client.Timeout = time.Millisecond * 100

uri := "https://httpbin.org/delay/3"
resp, err := client.Get(uri)
if err != nil {
    log.Fatalf("http.Get() failed with '%s'\n", err)
}

如图所示,创建和使用自定义http.Client很容易。

在此示例中,我们设置了非常短的超时,以证明超过该超时将取消连接。

在实际程序中,我们将使用更长的超时时间,例如15秒(确切的超时时间取决于代码的详细信息)。

基本的HTTP POST

client := &http.Client{}
client.Timeout = time.Second * 15

uri := "https://httpbin.org/post"
body := bytes.NewBufferString("text we send")
resp, err := client.Post(uri, "text/plain", body)
if err != nil {
    log.Fatalf("client.Post() failed with '%s'\n", err)
}
defer resp.Body.Close()
d, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatalf("http.Get() failed with '%s'\n", err)
}

fmt.Printf(“ http.Post()返回状态代码%d,截断的文本:\ n%s … \ n”,分别为StatusCode,字符串(d)[:93]) 进行POST的最简单方法是使用http.Client.Post(URL字符串,contentType字符串,body io.Reader)。

在此示例中,我们发送原始文本。 在大多数情况下,服务器期望正文为url编码格式。

基本HTTP HEAD 类似于HTTP GET,但使用http.Client.Head(uri字符串)方法。

HTTP POST

HTTP POST将二进制数据发送到服务器。

服务器如何解释此数据取决于Content-Type标头的值。

HTTP POST和url编码数据 HTTP POST最常用于将HTML页面中的表单数据提交给服务器。

表单数据是键/值对的字典,其中key是字符串,值是字符串数组(通常是带有单个元素的数组)。

表单键/值对最常作为URL编码的数据发送,其内容类型为application / x-www-form-urlencoded。

client := &http.Client{}
client.Timeout = time.Second * 15

uri := "https://httpbin.org/post"
data := url.Values{
    "name":  []string{"John"},
    "email": []string{"john@gmail.com"},
}
resp, err := client.PostForm(uri, data)
if err != nil {
    log.Fatalf("client.PosFormt() failed with '%s'\n", err)
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatalf("ioutil.ReadAll() failed with '%s'\n", err)
}

fmt.Printf("PostForm() sent '%s'. Response status code: %d\n", data.Encode(), resp.StatusCode)

JSON对象的PUT请求

http.Client没有方便的方法来执行PUT请求,因此我们构造了一个http.Request对象,并使用http.Client.Do(req * http.Request)来执行该请求。

user := User{
    Name:  "John Doe",
    Email: "johndoe@example.com",
}

d, err := json.Marshal(user)
if err != nil {
    log.Fatalf("json.Marshal() failed with '%s'\n", err)
}

client := &http.Client{}
client.Timeout = time.Second * 15

uri := "https://httpbin.org/put"
body := bytes.NewBuffer(d)
req, err := http.NewRequest(http.MethodPut, uri, body)
if err != nil {
    log.Fatalf("http.NewRequest() failed with '%s'\n", err)
}

req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := client.Do(req)
if err != nil {
    log.Fatalf("client.Do() failed with '%s'\n", err)
}

defer resp.Body.Close()
d, err = ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatalf("ioutil.ReadAll() failed with '%s'\n", err)
}

fmt.Printf("Response status code: %d, text:\n%s\n", resp.StatusCode, string(d))

带有上下文的超时请求

从Go 1.7开始,可以使用context.Context超时单个HTTP请求。

// httpbin.org is a service for testing HTTP client
// this URL waits 3 seconds before returning a response
uri := "https://httpbin.org/delay/3"
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
    log.Fatalf("http.NewRequest() failed with '%s'\n", err)
}

// create a context indicating 100 ms timeout
ctx, _ := context.WithTimeout(context.Background(), time.Millisecond*100)
// get a new request based on original request but with the context
req = req.WithContext(ctx)

resp, err := http.DefaultClient.Do(req)
if err != nil {
    // the request should timeout because we want to wait max 100 ms
    // but the server doesn't return response for 3 seconds
    log.Fatalf("http.DefaultClient.Do() failed with:\n'%s'\n", err)
}
defer resp.Body.Close()

带有URL参数和JSON响应的GET

本示例说明如何为GET请求正确编码URL参数,以及如何解析由Stack Exchange API返回的有关Stack Overflow帖子信息的JSON输出。

type postItem struct {
    Score int    `json:"score"`
    Link  string `json:"link"`
}

type postsType struct {
    Items []postItem `json:"items"`
}

values := url.Values{
    "order": []string{"desc"},
    "sort":  []string{"activity"},
    "site":  []string{"stackoverflow"},
}

// URL parameters can also be programmatically set
values.Set("page", "1")
values.Set("pagesize", "10")

uri := "https://api.stackexchange.com/2.2/posts?"
client := &http.Client{
    Timeout: 15 * time.Second,
}
resp, err := client.Get(uri + values.Encode())
if err != nil {
    log.Fatalf("http.Get() failed with '%s'\n", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
    d, _ := ioutil.ReadAll(resp.Body)
    log.Fatalf("Request was '%s' (%d) and not OK (200). Body:\n%s\n", resp.Status, resp.StatusCode, string(d))
}

dec := json.NewDecoder(resp.Body)
var p postsType
err = dec.Decode(&p)
if err != nil {
    log.Fatalf("dec.Decode() failed with '%s'\n", err)
}

fmt.Println("Top 10 most recently active StackOverflow posts:")
fmt.Println("Score", "Link")
for _, post := range p.Items {
    fmt.Println(post.Score, post.Link)
}

设置User-Agent

HTTP请求包括User-Agent标头。

最好使用对你的程序有意义的用户代理。

另外,某些服务器对它们接受的内容很挑剔。

这是设置自定义用户代理的方法:

userAgent := "Special Agent v 1.0.16"

client := &http.Client{}
client.Timeout = time.Second * 15

uri := "https://httpbin.org/user-agent"
req, err := http.NewRequest(http.MethodGet, uri, nil)
if err != nil {
    log.Fatalf("http.NewRequest() failed with '%s'\n", err)
}
req.Header.Set("User-Agent", userAgent)
resp, err := client.Do(req)
if err != nil {
    log.Fatalf("client.Do() failed with '%s'\n", err)
}

defer resp.Body.Close()
d, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatalf("ioutil.ReadAll() failed with '%s'\n", err)
}

fmt.Printf("Response status code: %d, text:\n%s\n", resp.StatusCode, string(d))

HTTP请求的方式

程序包net / http具有分层的设计,其中每一层都是位于较低层之上的便利包装。

每个较低的层都比较复杂,但是提供了更多的控制权。

这里是对执行HTTP GET请求的3种方式的概述。

使用http.Get()函数 最简单的方法是使用顶级http.Get()函数,但由于缺少超时,因此不建议使用。

使用http.Client.Get()方法 使用&http.Client {}创建* http.Client 设置适当的超时 使用其Get()或Post()或PostForm()方法 使用http.Client.Do()方法 这样可以最大程度地控制请求。

创建http.Client并设置适当的超时 使用http.NewRequest创建* http.Request 将其方法设置为“ GET”,“ POST”,“ HEAD”,“ PUT”或“ DELETE” 设置自定义标头,例如User-Agentwith Header.Set(key,value string) 通过设置io.ReadCloser类型的主体来设置要发送的主体 设置TransferEncoding 与client.Do(req * http.Request)发送请求 通过使用上下文包含截止期限req = request.WithContext(ctx)的新请求来设置每个请求超时 这是执行PUT或DELETE请求的唯一方法。


相关

最新