上篇文章 Go HTTP 调用(上) 介绍了如何进行 HTTP 调用,并通过 GET 请求的例子,讲述了 query
参数和 header
参数如何设置,以及响应体的获取方法。 本文继上文,接下来会通过 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
参数的如何传递,上下两篇文章已经通过例子进行介绍。虽然举的例子是 GET
和 POST
请求,如果想要调用 PUT
、DELETE
等请求,只需要在 NewRequestWithContext
函数中,指定第二个参数为 http.MethodPut
、http.MethodDelete
等就行。