通过Go语言实现Http请求 http.Post import ( "net/http" "net/url" ) data := url.Values{"start
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方法
客户端:
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))
}
解析:
注意(坑):
1、header里的参数是Content-Type,不要写成ContentType
2、【go http: read on closed response body 】如果发送的请求是分为2个func写的,记住defer要在ioutil.ReadAll之后执行,否则报错
这种方式适合在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))
}
到此这篇关于golang NewRequest/gorequest实现http请求的示例代码的文章就介绍到这了,更多相关golang http请求内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: golangNewRequest/gorequest实现http请求的示例代码
本文链接: https://lsjlt.com/news/120979.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-05
2024-04-05
2024-04-05
2024-04-04
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-04
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0