Go HTTP 调用(下)

耐心和持久胜过激烈和狂热。

哈喽大家好,我是陈明勇,今天分享的内容是 Go HTTP 调用。如果本文对你有帮助,不妨点个赞,如果你是 Go 语言初学者,不妨点个关注,一起成长一起进步,如果本文有错误的地方,欢迎指出!

前言

上篇文章 Go HTTP 调用(上) 介绍了如何进行 HTTP 调用,并通过 GET 请求的例子,讲述了 query 参数和 header 参数如何设置,以及响应体的获取方法。 本文继上文,接下来会通过 POST 请求,对其他参数的设置进行介绍。

POST 请求

发起 HTTP POST 请求时,携带 json 格式的 body 参数是最常见的,这是因为 json 格式的参数可读性好,对于层级结构较为复杂的数据也能应对,并且这符合 RestFul API 的规范。因此以下的示例为:发送 HTTP POST 请求,并携带 json 类型的 body 参数。


import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

type User struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func main() {
	client := http.Client{}

	user := User{
		Username: "123456",
		Password: "12346",
	}
	dataByte, err := json.Marshal(user)
	if err != nil {
		fmt.Println(err)
	}
	bodyReader := bytes.NewReader(dataByte)

	request, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "http://localhost:8080/user", bodyReader)
	if err != nil {
		return
	}
	request.Header.Set("Content-Type", "application/json")
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("statusCode: ", resp.StatusCode)
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	fmt.Println(string(body))
}

  • 首先定义 User 结构体,创建结构体变量 user,通过 json.Marshal 函数,将 user 转成 []byte 数据,然后通过 bytes.NewReader 函数,将 []byte 数据转成 Reader 指针变量。
  • http.NewRequestWithContext 函数,最后一个参数是为 body 参数,接收的变量类型是 Reader 接口的实现体。第一步将 user 转成 Reader 指针变量就是为了在这里进行传递。
  • 传递 json 类型的 body 参数,需要在请求头参数里设置 Content-Type 的值为 application/json
  • 如果是发送 application/x-www-form-urlencoded 类型的表单数据,需要改写 body 参数的生成代码:
    values := url.Values{}
    values.Set("username", "1234")
    values.Set("password", "1234")
    bodyReader := strings.NewReader(values.Encode())
    

小结

本文通过 POST 请求,介绍了如何传递 json 类型和 application/x-www-form-urlencoded 类型的 body 参数。对于 HTTP 中的 query 参数和 body 参数的如何传递,上下两篇文章已经通过例子进行介绍。虽然举的例子是 GETPOST 请求,如果想要调用 PUTDELETE 等请求,只需要在 NewRequestWithContext 函数中,指定第二个参数为 http.MethodPuthttp.MethodDelete 等就行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Go-RequestHTTP 客户端请求包,灵感来源于 Python Requests。 安装 go get -u github.com/mozillazg/request 文档 API 文档:https://godoc.org/github.com/mozillazg/request 使用 import (     "github.com/mozillazg/request" ) GET: c := new(http.Client) req := request.NewRequest(c) resp, err := req.Get("http://httpbin.org/get") j, err := resp.Json() defer resp.Body.Close()  // Don't forget close the response body POST: req.Data = map[string]string{     "key": "value",     "a":   "123", } resp, err := req.Post("http://httpbin.org/post") Cookies: req.Cookies = map[string]string{     "key": "value",     "a":   "123", } resp, err := req.Get("http://httpbin.org/cookies") Headers: req.Headers = map[string]string{     "Accept-Encoding": "gzip,deflate,sdch",     "Accept": "text/html,application/xhtml xml,application/xml;q=0.9,image/webp,*/*;q=0.8", } resp, err := req.Get("http://httpbin.org/get") Files: f, err := os.Open("test.txt") req.Files = []request.FileField{     request.FileField{"file", "test.txt", f}, }resp, err := req.Post("http://httpbin.org/post") Json: req.Json = map[string]string{    "a": "A",    "b": "B", }resp, err := req.Post("http://httpbin.org/post") req.Json = []int{1, 2, 3} resp, err = req.Post("http://httpbin.org/post") Proxy: req.Proxy = "http://127.0.0.1:8080" // req.Proxy = "https://127.0.0.1:8080" // req.Proxy = "socks5://127.0.0.1:57341" resp, err := req.Get("http://httpbin.org/get") or https://github.com/mozillazg/request/tree/develop/_example/proxy HTTP Basic Authentication: req.BasicAuth = request.BasicAuth{"user", "passwd"} resp, err := req.Get("http://httpbin.org/basic-auth/user/passwd") 标签:GoRequest

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员陈_明勇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值