×

Go语言实现简单的GET POST发送

admin admin 发表于2021-12-17 16:13:54 浏览162 评论0

抢沙发发表评论

1:实现GET请求的方法

resp, err := http.Get("http://example.com/")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
 
if err != nil {
// handle error
}
 
fmt.Println(string(body))



2:post请求

resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
 
if err != nil {
// handle error
}
 
fmt.Println(string(body))



3:post表单请求


postValue := url.Values{
"email": {"xx@xx.com"},
"password": {"123456"},
}
 
resp, err := http.PostForm("http://example.com/login", postValue)
if err != nil {
// handle error
}
 
defer resp.Body.Close()
 
body, err := ioutil.ReadAll(resp.Body)
 
if err != nil {
// handle error
}
 
fmt.Println(string(body))
postValue := url.Values{
"email": {"xx@xx.com"},
"password": {"123456"},
}
 
postString := postValue.Encode()
 
req, err := http.NewRequest("POST","http://example.com/login_ajax", strings.NewReader(postString))
if err != nil {
// handle error
}
 
// 表单方式(必须)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
//AJAX 方式请求
req.Header.Add("x-requested-with", "XMLHttpRequest")
 
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// handle error
}
 
defer resp.Body.Close()
 
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
 
fmt.Println(string(body))