耐心和持久胜过激烈和狂热。
哈喽大家好,我是陈明勇,今天分享的内容是 Go HTTP 调用。如果本文对你有帮助,不妨点个赞,如果你是 Go 语言初学者,不妨点个关注,一起成长一起进步,如果本文有错误的地方,欢迎指出!
前言queryheaderPOST
POST 请求
HTTPPOSTjsonbodyjsonRestFul APIHTTPPOSTjsonbody
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))
}
values := url.Values{}
values.Set("username", "1234")
values.Set("password", "1234")
bodyReader := strings.NewReader(values.Encode())
小结
POSTjsonapplication/x-www-form-urlencodedbodyHTTPquerybodyGETPOSTPUTDELETENewRequestWithContexthttp.MethodPuthttp.MethodDelete