日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

golang?NewRequest/gorequest實現(xiàn)http請求的示例代碼_Golang

作者:我的貓叫土豆 ? 更新時間: 2022-10-02 編程語言

通過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為標(biāo)準(zhǔn)格式

注意(坑):

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))
}

原文鏈接:https://blog.csdn.net/ambzheng/article/details/104483754

欄目分類
最近更新