【二、http】go的http基本请求设置(设置查询参数、定制请求头)get和post类似

一、设置url后边的参数,(get和post请求为例子)

cpp 复制代码
func requstByParamsGet(){
	requst, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get", nil)
	if err != nil {
		fmt.Println("ss")
	}

	params := make(url.Values)
	params.Add("name", "kaiyue")
	params.Add("age", "18")

	//encode之后会生成如下,name=kaiyue&age=18
	requst.URL.RawQuery = params.Encode()
	r, err := http.DefaultClient.Do(requst)
	if err != nil {
		fmt.Println("ss")
	}
	defer r.Body.Close()
	printBody(r)
}

func requstByParamsPost(){
	requst, err := http.NewRequest(http.MethodPost, "http://httpbin.org/post", nil)
	if err != nil {
		fmt.Println("ss")
	}

	params := make(url.Values)
	params.Add("name", "kaiyue")
	params.Add("age", "18")

	//encode之后会生成如下,name=kaiyue&age=18, 是组成url问号后边的参数
	requst.URL.RawQuery = params.Encode()
	r, err := http.DefaultClient.Do(requst)
	if err != nil {
		fmt.Println("ss")
	}
	defer r.Body.Close()
	printBody(r)
}
func main() {
	requstByParamsPost()
}

结果:

cpp 复制代码
{
  "args": {
    "age": "18", 
    "name": "kaiyue"
  }, 
  "data": "", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Content-Length": "0", 
    "Host": "httpbin.org", 
    "User-Agent": "Go-http-client/1.1", 
    "X-Amzn-Trace-Id": "Root=1-6544e26c-2a47c0392e3351a71259c068"
  }, 
  "json": null, 
  "origin": "120.244.60.192", 
  "url": "http://httpbin.org/post?age=18&name=kaiyue"
}

二、定制http头中的参数

cpp 复制代码
func requstByHeader(){
	requst, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get", nil)
	if err != nil {
		fmt.Println("ss")
	}

	requst.Header.Add("user-agent", "chrome")
	r, err := http.DefaultClient.Do(requst)
	if err != nil {
		fmt.Println("ss")
	}
	defer r.Body.Close()
	printBody(r)
}

func main() {
	requstByHeader()
}

结果:

cpp 复制代码
{
  "args": {}, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Host": "httpbin.org", 
    "User-Agent": "chrome", 
    "X-Amzn-Trace-Id": "Root=1-6544e394-14143f26584a7eed32728fd7"
  }, 
  "origin": "120.244.60.192", 
  "url": "http://httpbin.org/get"
}

可以看到其中头部信息已经打印出自己增加的部分内容

相关推荐
2501_915921435 小时前
iOS 应用上架多环境实战,Windows、Linux 与 Mac 的不同路径
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张10 小时前
iOS 应用上架常见问题与解决方案,多工具组合的实战经验
android·ios·小程序·https·uni-app·iphone·webview
AirDroid_cn18 小时前
PDF转图片需要用到什么技术?苹果手机怎样将PDF转为jpg?
pdf·iphone·ipad·快捷指令
rainFFrain1 天前
Boost搜索引擎项目(详细思路版)
网络·c++·http·搜索引擎
2501_916007471 天前
iOS App 上架实战 从内测到应用商店发布的全周期流程解析
android·ios·小程序·https·uni-app·iphone·webview
猿究院--冯磊1 天前
计算机网络--HTTP协议
网络协议·计算机网络·http
bianshaopeng1 天前
ubuntu go 环境变量配置
开发语言·ubuntu·golang
元清加油1 天前
【Goland】:协程和通道
服务器·开发语言·后端·网络协议·golang
让代码飞~1 天前
idea进阶技能掌握, 使用自带HTTP测试工具,完全可替代PostMan
java·http·intellij-idea·postman
lpfasd1231 天前
01_Go语言基础与环境搭建
开发语言·后端·golang