golang NewRequest/gorequest實現(xiàn)http請求的示例代碼
通過go語言實現(xiàn)http請求
http.Post
import (
?? ?"net/http"
?? ?"net/url"
)
data := url.Values{"start":{"100"}, "hobby":{"xxxx"}}
body := strings.NewReader(data.Encode())
resp, err := http.Post("127.0.0.1:9338", "application/x-www-form-urlencoded", body)net/http包沒有封裝直接使用請求帶header的get或者post方法,所以,要想請求中帶header,只能使用NewRequest方法
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):創(chuàng)建url
- response,err := client.Do(request):客戶端發(fā)起請求,接收返回值
- body,err := ioutil.ReadAll(response.Body):讀取body的值,類型是byte
- json.MarshalIndent(stuReq):修改json為標準格式
注意(坑):
1、header里的參數(shù)是Content-Type,不要寫成ContentType
2、【go http: read on closed response body 】如果發(fā)送的請求是分為2個func寫的,記住defer要在ioutil.ReadAll之后執(zhí)行,否則報錯
gorequest
這種方式適合在url里拼接參數(shù)使用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))
}到此這篇關于golang NewRequest/gorequest實現(xiàn)http請求的示例代碼的文章就介紹到這了,更多相關golang http請求內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Go簡單實現(xiàn)協(xié)程池的實現(xiàn)示例
本文主要介紹了Go簡單實現(xiàn)協(xié)程池的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06

