首先!刚刚开始接触GO语言,感觉还是非常强大的,最近在学习中也有很多自己的想法,也尝试子写了一些东西,记录一下加深印象!
标题 GO语言的post请求和get请求
1.post
有两种 (1)http.postForm
(2)http.post
第一种是一种表单形式的请求,后面可以加上你想附带的 username,password或者验证码
比如这种
var resp *http.Response
//ResponseBody := new(ResponseBody)
resp, err := http.PostForm("http://localhost/server/index.php?s=/api/user/login", url.Values{"username": {"xkxk"}, "password": {"kxk"}, "v_code": {"123"}})
if err != nil {
fmt.Println("POST请求:创建请求失败", err)
}
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
} else {
fmt.Println("err ")
}
第二种是在里面设置的
¥¥¥¥重点来了¥¥¥¥
使用这个方法的话,第二个参数要设置成”application/x-www-form-urlencoded”,否则post参数无法传递。
func httpPost() {
resp, err := http.Post("http://www.01happy.com/demo/accept.php",
"application/x-www-form-urlencoded",
strings.NewReader("name=cjb"))
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))
}
2.get
get 请求相对与会简单一点,直接请求就好
func httpGet() {
resp, err := http.Get("http://www.01happy.com/demo/accept.php?id=1")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
当然最后还有一点,就是最麻烦的,我们在请求的时候想设定一些参数怎么办呢
比如 我做过的一个需求 需要用cookie去请求一个列表这个时候看这里
func httpDo() {
client := &http.Client{}
req, err := http.NewRequest("POST", "http://www.showdoc.cc", strings.NewReader("name=cjb"))
if err != nil {
// handle error
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Cookie", "name=anny")
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
用 req.Header.Set方法 可以把你想传进去的值 传进去
(哈哈,最后最后,欢迎大佬来指点错误,一起交流,一起学习!)