这个我忘记是哪位大神哪里抄的代码,觉得很好就保留在这里,自己用的时候好参考
package demo
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
func HttpGet() {
resp,err := http.Get("http://mini.helloworld.com/index.php?r=demo/test")
if err != nil {
//handler err
}
defer resp.Body.Close()
body,err := ioutil.ReadAll(resp.Body)
if err != nil {
//handler error
}
fmt.Println(string(body))
}
func HttpPost() {
resp,err := http.Post("http://mini.helloworld.com/index.php?r=demo/post" ,
"application/x-www-form-urlencoded",
strings.NewReader("name=cjb&hi=wuping&t=1"))
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body,err := ioutil.ReadAll(resp.Body);
if err != nil {
//handler error
}
fmt.Println(string(body))
}
func HttpPostForm() {
resp,err := http.PostForm("http://mini.helloworld.com/index.php?r=demo/post",
url.Values{"key":{"Value"},"id":{"123"},"name":{"wuping"}})
if err != nil {
//handler error
}
defer resp.Body.Close()
body,err := ioutil.ReadAll(resp.Body)
if err != nil {
//handler error
}
fmt.Println(string(body))
}
func HttpDo() {
client := &http.Client{}
req,err := http.NewRequest("POST","http://mini.helloworld.com/index.php?r=demo/post",strings.NewReader("name=cjb&today=4.1"))
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))
}