比较简单的方式有两个:(下面的代码是抄的)
1.http.post()/http.get()
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.http.Client.DO()
func httpDo() {
client := &http.Client{}
req, err := http.NewRequest("POST", "http://www.01happy.com/demo/accept.php", strings.NewReader("name=cjb")) //bytes.NewReader()
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))
}
3.net url
参考 :https://blog.csdn.net/typ2004/article/details/38669949
u, _ := url.Parse("http://localhost:9001/xiaoyue")
q := u.Query()
q.Set("username", "user")
q.Set("password", "passwd")
u.RawQuery = q.Encode()
res, err := http.Get(u.String());
4.不确定返回body的数据时如何解析
例子和3一样是出自:https://blog.csdn.net/typ2004/article/details/38669949
result, _:= ioutil.ReadAll(r.Body)
r.Body.Close()
fmt.Printf("%s\n", result)
//未知类型的推荐处理方法
var f interface{}
json.Unmarshal(result, &f)
m := f.(map[string]interface{})
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case int:
fmt.Println(k, "is int", vv)
case float64:
fmt.Println(k,"is float64",vv)
case []interface{}:
fmt.Println(k, "is an array:")
for i, u := range vv {
fmt.Println(i, u)
}
default:
fmt.Println(k, "is of a type I don't know how to handle")
}
}
参考:
这两篇都不太好,不过例子可以跑通。
https://www.cnblogs.com/mafeng/p/7068837.html
https://studygolang.com/articles/4830