【二、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"
}

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

相关推荐
moonless02221 天前
FastAPI框架,这一小篇就能搞懂精髓。
http·fastapi
2501_915918412 天前
iOS 上架全流程指南 iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传 ipa 与审核实战经验分享
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张2 天前
iOS App 混淆与加固对比 源码混淆与ipa文件混淆的区别、iOS代码保护与应用安全场景最佳实践
android·安全·ios·小程序·uni-app·iphone·webview
ftpeak2 天前
从零开始使用 axum-server 构建 HTTP/HTTPS 服务
网络·http·https·rust·web·web app
00后程序员张2 天前
详细解析苹果iOS应用上架到App Store的完整步骤与指南
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 天前
Xcode 上传 ipa 全流程详解 App Store 上架流程、uni-app 生成 ipa 文件上传与审核指南
android·macos·ios·小程序·uni-app·iphone·xcode
o0o_-_3 天前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang
2301_821046523 天前
Python与Go结合
ios·iphone
weixin_456904273 天前
使用HTTPS 服务在浏览器端使用摄像头的方式解析
网络协议·http·https
Digitally3 天前
如何将大型音频文件从 iPhone 发送到不同的设备
ios·iphone