1、get请求可以直接http.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))
}
1、一种是使用http.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、postform案例
书写客户端
package main
import (
"fmt"
"net/http"
"net/url"
)
func main() {
//这里添加post的body内容
data := make(url.Values)
data["key"] = []string{"this is key"}
data["value"] = []string{"this is value"}
//把post表单发送给目标服务器
res, err := http.PostForm("http://127.0.0.1/postpage", data)
if err != nil {
fmt.Println(err.Error())
return
}
defer res.Body.Close()
fmt.Println("post send success")
}
3、使用http.postform方式
func httpPostForm() {
resp, err := http.PostForm("http://www.01happy.com/demo/accept.php",
url.Values{"key": {"Value"}, "id": {"123"}})
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
原文:https://www.cnblogs.com/wuchangblog/p/14929094.html