文章目录
1. GET请求
func httpGet() {
resp, err := http.Get("http://www.baidu.com")
if err != nil {
// handle error
fmt.Println(err.Error())
}
defer resp.body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
fmt.Println(err.Error())
}
fmt.Println(string(body))
}
2. post请求
1. http.Post方式
func httpPost() {
// 使用这个方法的话,第二个参数要设置成”application/x-www-form-urlencoded”,否则post参数无法传递。
resp, err := http.Post("127.0.0.1:8080/user/login",
"application/x-www-form-urlencoded",
strings.NewReader("name=zhangsan"))
if err != nil {
fmt.Println(err.Error())
} else {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
fmt.Println(err.Error())
}
fmt.Println(string(body))
}
}
2. http.PostForm方法
func httpPostForm() {
resp, err := http.PostForm("127.0.0.1:8080/user/login",
url.Values{"name": {"zhangsan"}, "password": {"123456"}})
if err != nil {
fmt.Println(err.Error())
} else {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
fmt.Println(err.Error())
}
fmt.Println(string(body))
}
}
3. 比较复杂的请求,http.Do方法
//有时需要在请求的时候设置头参数、cookie之类的数据,就可以使用http.Do方法。
1. 使用strings.NewReader()传参
func httpDo(name string, password string) {
client := &http.Client{}
// 设置请求体
data := url.Values{}
// key,value必须为字符串类型
data.Add("name", name)
data.Add("password", password)
// 请求中三个参数依次为 请求方法, 请求url, 请求体
req, err := http.NewRequest("POST", "127.0.0.1:8080/user/login", strings.NewReader(data.Encode()))
if err != nil {
// handle error
}
// 设置请求头
//必须要设定Content-Type为application/x-www-form-urlencoded,post参数才可正常传递
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
2. 使用bytes.NewBuffer()传参
// url:请求地址,data:POST请求提交的数据,contentType:请求体格式,如:application/json
func Post(url string, data interface{}, contentType string) string {
jsonStr, _ := json.Marshal(data)
req, err := http.NewRequest(`POST`, url, bytes.NewBuffer(jsonStr))
req.Header.Add(`content-type`, contentType)
if err != nil {
panic(err)
}
defer req.Body.Close()
// 设置超时时间
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
result, _ := ioutil.ReadAll(resp.Body)
return string(result)
}