golang常用的http请求操作 GET POST总结汇总
时间:2022-04-14
本文章向大家介绍golang常用的http请求操作 GET POST总结汇总,主要包括golang常用的http请求操作 GET POST总结汇总使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
下面主要整理了常用的通过golang发起的GET请求以及POST请求的代码例子
1.golang发起GET请求
基本GET请求
//基本的GET请求 package main import ( "fmt" "io/ioutil" "net/http" ) func main() { resp, err := http.Get("http://httpbin.org/get") if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) fmt.Println(resp.StatusCode) if resp.StatusCode == 200 { fmt.Println("ok") } }
带参数的Get请求
package main import ( "fmt" "io/ioutil" "net/http" ) func main(){ resp, err := http.Get("http://httpbin.org/get?name=zhaofan&age=23") if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
但是如果我们想要把一些参数做成变量而不是直接放到url中怎么操作,代码例子如下:
package main import ( "fmt" "io/ioutil" "net/http" "net/url" ) func main(){ params := url.Values{} Url, err := url.Parse("http://httpbin.org/get") if err != nil { return } params.Set("name","zhaofan") params.Set("age","23") //如果参数中有中文参数,这个方法会进行URLEncode Url.RawQuery = params.Encode() urlPath := Url.String() fmt.Println(urlPath) // https://httpbin.org/get?age=23&name=zhaofan resp,err := http.Get(urlPath) defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
解析JSON类型的返回结果
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" ) type result struct { Args string `json:"args"` Headers map[string]string `json:"headers"` Origin string `json:"origin"` Url string `json:"url"` } func main() { resp, err := http.Get("http://httpbin.org/get") if err != nil { return } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) var res result _ = json.Unmarshal(body,&res) fmt.Printf("%#v", res) }
GET请求添加请求头
package main import ( "fmt" "io/ioutil" "net/http" ) func main() { client := &http.Client{} req,_ := http.NewRequest("GET","http://httpbin.org/get",nil) req.Header.Add("name","zhaofan") req.Header.Add("age","3") resp,_ := client.Do(req) body, _ := ioutil.ReadAll(resp.Body) fmt.Printf(string(body)) }
从上述的结果可以看出我们设置的头是成功了:
{ "args": {}, "headers": { "Accept-Encoding": "gzip", "Age": "3", "Host": "httpbin.org", "Name": "zhaofan", "User-Agent": "Go-http-client/1.1" }, "origin": "211.138.20.170, 211.138.20.170", "url": "https://httpbin.org/get" }
2.golang 发起POST请求
基本的POST使用
package main import ( "fmt" "io/ioutil" "net/http" "net/url" ) func main() { urlValues := url.Values{} urlValues.Add("name","zhaofan") urlValues.Add("age","22") resp, _ := http.PostForm("http://httpbin.org/post",urlValues) body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
结果如下:
{ "args": {}, "data": "", "files": {}, "form": { "age": "22", "name": "zhaofan" }, "headers": { "Accept-Encoding": "gzip", "Content-Length": "19", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "Go-http-client/1.1" }, "json": null, "origin": "211.138.20.170, 211.138.20.170", "url": "https://httpbin.org/post" }
另外一种方式
package main import ( "fmt" "io/ioutil" "net/http" "net/url" "strings" ) func main() { urlValues := url.Values{ "name":{"zhaofan"}, "age":{"23"}, } reqBody:= urlValues.Encode() resp, _ := http.Post("http://httpbin.org/post", "text/html",strings.NewReader(reqBody)) body,_:= ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
结果如下:
{ "args": {}, "data": "age=23&name=zhaofan", "files": {}, "form": {}, "headers": { "Accept-Encoding": "gzip", "Content-Length": "19", "Content-Type": "text/html", "Host": "httpbin.org", "User-Agent": "Go-http-client/1.1" }, "json": null, "origin": "211.138.20.170, 211.138.20.170", "url": "https://httpbin.org/post" }
发送JSON数据的post请求
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) func main() { client := &http.Client{} data := make(map[string]interface{}) data["name"] = "zhaofan" data["age"] = "23" bytesData, _ := json.Marshal(data) req, _ := http.NewRequest("POST","http://httpbin.org/post",bytes.NewReader(bytesData)) resp, _ := client.Do(req) body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
结果如下:
{ "args": {}, "data": "{\"age\":\"23\",\"name\":\"zhaofan\"}", "files": {}, "form": {}, "headers": { "Accept-Encoding": "gzip", "Content-Length": "29", "Host": "httpbin.org", "User-Agent": "Go-http-client/1.1" }, "json": { "age": "23", "name": "zhaofan" }, "origin": "211.138.20.170, 211.138.20.170", "url": "https://httpbin.org/post" }
不用client的post请求
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) func main() { data := make(map[string]interface{}) data["name"] = "zhaofan" data["age"] = "23" bytesData, _ := json.Marshal(data) resp, _ := http.Post("http://httpbin.org/post","application/json", bytes.NewReader(bytesData)) body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
原文地址:https://www.cnblogs.com/zhaoyingjie/p/16145453.html
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- dotnet OpenXML 幻灯片 PPTX 的 Slide Id 和页面序号的关系
- springboot 国际化
- Windows/Android/iOS全平台支持的视频播放器EasyPlayerPro,iOS版播放无音频问题如何解决?
- java之springboot之快速入门(一)- maven方式创建项目
- java之springboot之快速入门-Spring Initializr方式创建项目
- springboot之Web综合开发
- springboot之mybatis
- springboot之mybatis多数据源最简解决方案
- 蓝桥杯突击复习准备——部分算法汇总
- 小解c# foreach原理
- 多包依赖管理--Lerna
- Flume概述
- Flume中常见的组件
- 程序员进阶之算法练习(四十八)LeetCode
- [C#]不通过事件方式获取键盘按钮按下的状态