通過go語言實現http請求
http.NewRequest
客戶端:
import (
"net/http"
"json"
"ioutil"
)
type Student struct{
id string
name string
}
type StudentReq struct{
id string
name string
}
func main() {
stu := Student{
id:"2ed4tg5fe35fgty3yy6uh",
name:"amber",
}
stu,err := json.Marshal(&stu)
reader := bytes.NewReader(stu)
request,err := http.NewRequest("POST", "http://192.168.1.12:8000/create", reader)
request.Header.Set("Content-Type", "application/json")
client:=&http.Client{}
response,err := client.Do(request)
defer response.Body.Close()
body,err := ioutil.ReadAll(response.Body)
fmt.Printf(string(body))
var stuReq StudentReq
err = json.UnMarshal(body, &stuReq)
fmt.Println(json.MarshalIndent(stuReq))
}
解析:
- stu,err := json.Marshal(&stu):將stu對象改爲json格式
- reader := bytes.NewReader(stu):所以將json改爲byte格式,作爲body傳給http請求
- request,err := http.NewRequest(“POST”, “http://192.168.1.12:8000/create”, reader):創建url
- response,err := client.Do(request):客戶端發起請求,接收返回值
- body,err := ioutil.ReadAll(response.Body):讀取body的值,類型是byte
- json.MarshalIndent(stuReq):修改json爲標準格式
注意(坑):
1、header裏的參數是Content-Type,不要寫成ContentType
2、【go http: read on closed response body 】如果發送的請求是分爲2個func寫的,記住defer要在ioutil.ReadAll之後執行,否則報錯
gorequest
這種方式適合在url裏拼接參數使用param直接傳遞
"github.com/parnurzeal/gorequest"
func main() {
resp, body, errs := gorequest.New().Post("http://127.0.0.1/create").Param("ip", "192.168.1.4").EndBytes()
if errs != nil || resp.StatusCode >= 300 {
log.Errorf("fail to call api with errors %v, %+v", errs, body)
}
var stuReq StudentReq
err = json.UnMarshal(body, &stuReq)
fmt.Println(json.MarshalIndent(stuReq))
}