post请求常用的几种方式,记录一下
func httpPost() {
resp, err := http.Post("https://www.abcd123.top/api/v1/login",
"application/x-www-form-urlencoded",
strings.NewReader("username=test&password=ab123123"))
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func httpPostForm() {
resp, err := http.PostForm("https://www.denlery.top/api/v1/login",
url.Values{"username": {"auto"}, "password": {"auto123123"}})
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func httpPostJson() {
jsonStr :=[]byte(`{ "username": "auto", "password": "auto123123" }`)
url:= "https://www.denlery.top/api/v1/login"
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// handle error
}
defer resp.Body.Close()
statuscode := resp.StatusCode
hea := resp.Header
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
fmt.Println(statuscode)
fmt.Println(hea)
}
本文介绍了使用Go语言发送POST请求的三种常见方法:通过http.Post直接发送表单数据、使用http.PostForm简化表单发送过程及利用http.NewRequest构造JSON格式的数据请求。这些方法覆盖了不同场景下的需求。

2093

被折叠的 条评论
为什么被折叠?



