本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
golang NewRequest/gorequest实现http请求的示例代码
makebo · 236浏览 · 发布于2022-08-08 +关注

本文主要介绍了golang NewRequest/gorequest实现http请求的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

通过go语言实现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):创建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))
}

到此这篇关于golang NewRequest/gorequest实现http请求的示例代码的文章就介绍到这了,


相关推荐

PHP实现部分字符隐藏

沙雕mars · 1312浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 896浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 957浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 953浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1077浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
没有最好,只有更好,一切都在路上!
分类专栏
小鸟云服务器
扫码进入手机网页