Go语言Http调用之Post请求详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Go语言Http调用之Post请求详解

陈明勇   2022-12-15 我要评论

前言

上篇文章 Go HTTP 调用(上) 介绍了如何进行 HTTP 调用,并通过 GET 请求的例子,讲述了 query 参数和 header 参数如何设置,以及响应体的获取方法。 本文继上文,接下来会通过 POST 请求,对其他参数的设置进行介绍。

POST 请求

发起 HTTP POST 请求时,携带 json 格式的 body 参数是最常见的,这是因为 json 格式的参数可读性好,对于层级结构较为复杂的数据也能应对,并且这符合 RestFul API 的规范。因此以下的示例为:发送 HTTP POST 请求,并携带 json 类型的 body 参数。

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

type User struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

func main() {
    client := http.Client{}

    user := User{
        Username: "123456",
        Password: "12346",
    }
    dataByte, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
    }
    bodyReader := bytes.NewReader(dataByte)

    request, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "http://localhost:8080/user", bodyReader)
    if err != nil {
        return
    }
    request.Header.Set("Content-Type", "application/json")
    resp, err := client.Do(request)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("statusCode: ", resp.StatusCode)
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return
    }
    defer resp.Body.Close()
    fmt.Println(string(body))
}
  • 首先定义 User 结构体,创建结构体变量 user,通过 json.Marshal 函数,将 user 转成 []byte 数据,然后通过 bytes.NewReader 函数,将 []byte 数据转成 Reader 指针变量。
  • http.NewRequestWithContext 函数,最后一个参数是为 body 参数,接收的变量类型是 Reader 接口的实现体。第一步将 user 转成 Reader 指针变量就是为了在这里进行传递。
  • 传递 json 类型的 body 参数,需要在请求头参数里设置 Content-Type 的值为 application/json

如果是发送 application/x-www-form-urlencoded 类型的表单数据,需要改写 body 参数的生成代码:

values := url.Values{}
values.Set("username", "1234")
values.Set("password", "1234")
bodyReader := strings.NewReader(values.Encode())

小结

本文通过 POST 请求,介绍了如何传递 json 类型和 application/x-www-form-urlencoded 类型的 body 参数。对于 HTTP 中的 query 参数和 body 参数的如何传递,上下两篇文章已经通过例子进行介绍。虽然举的例子是 GETPOST 请求,如果想要调用 PUTDELETE 等请求,只需要在 NewRequestWithContext 函数中,指定第二个参数为 http.MethodPuthttp.MethodDelete 等就行。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们