本文是原创文章,以后我踩过的golang或python的坑,都会在此和大家分享,共同进步!
百度搜索出来的Post调用方式,无论是 http.PostForm方式:
func post(){
resp, err :=
http.PostForm("http://127.0.0.1",
url.Values{"name": {"terrygmx"}, "blog": {"https://blog.csdn.net/terrygmx"},
"hobby":{"python golang"},"content":{"something "}})
}
亦或是 http.NewRequest 方式
data := url.Values{}
data.Set("client_id", `Lazy Test`)
data.Add("client_secret", clientSecret)
data.Add("grant_type", "client_credentials")
req, err := http.NewRequest("POST", yourUrl, bytes.NewBufferString(data.Encode()))
可以看到都用到了 url.Values
这个url.Values 使用起来的确方便,和构造字典挺像。但是我们看看其源码:
type Values map[string][]string
可知实际上它被定义成了字符串数组。因此像以下的嵌套型Json作为data,用url.Values是不能产生的:
{"学校班级信息":
{"班级信息":
{"班级":"0212",
"学号":"2002-2006"}
}
}
是用字节切片解决。
reqBody := []byte(`{"学校班级信息":
{"班级信息":
{"班级":"0212",
"学号":"2002-2006"}
}
}`)
req, _ :=
http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/js"nq)
resp, err := client.Do(req)
完整示例代码:
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
post()
}
func post() {
client := &http.Client{}
reqBody := []byte(`{"学校班级信息":
{"班级信息":
{"班级":"0212",
"学号":"2002-2006"}
}
}`)
url := "HTTP://localhost:80/yourAPI"
req, _ :=
http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
if err != nil {
panic(err)
}
fmt.Println("response Body:", string(body))
}