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

解析:

  1. stu,err := json.Marshal(&stu):将stu对象改为json格式
  2. reader := bytes.NewReader(stu):所以将json改为byte格式,作为body传给http请求
  3. request,err := http.NewRequest(“POST”, “http://192.168.1.12:8000/create”, reader):创建url
  4. response,err := client.Do(request):客户端发起请求,接收返回值
  5. body,err := ioutil.ReadAll(response.Body):读取body的值,类型是byte
  6. 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))
}

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值