go发送http的get请求
package main
import (
"fmt"
"io/ioutil" //io模块
"net/http" //http服务模块
)
func main() {
//go 发送http的get请求
//response, err := http.Get("http://www.baidu.com")
response, err := http.Get("http://o.baidu.com")
//如果发送失败
if err != nil {
//handle error
fmt.Println("发送get请求报错了。")
}
//这里是析构函数关闭body请求
defer response.Body.Close()
//读取响应的body
body, _ := ioutil.ReadAll(response.Body)
//打印响应的body
fmt.Println(string(body))
}
go发送http的post请求
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
//http post 请求
body := "{\"action\":20}"
res, err := http.Post("https://passport.baidu.com/v2/api/?login", "application/json:charset=utf-8", bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Fatal error", err.Error())
}
defer res.Body.Close()
content, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Fatal error", err.Error())
}
fmt.Println(string(content))
}