golang常用的http请求操作
之前用python写各种网络请求的时候写的非常顺手,但是当打算用golang写的时候才发现相对来说还是python的那种方式用的更加顺手,习惯golang的用法之后也就差别不大了,下面主要整理了常用的通过golang发起的GET请求以及POST请求的代码例子
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"
}
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))
}
golang常用的http请求操作的更多相关文章
- Golang: 常用的文件读写操作
Go 语言提供了很多文件操作的支持,在不同场景下,有对应的处理方式,今天就来系统地梳理一下,几种常用的文件读写的形式. 一.读取文件内容 1.按字节读取文件 这种方式是以字节为单位来读取,相对底层一些 ...
- HTTP消息头(HTTP headers)-常用的HTTP请求头与响应头
HTTP消息头是指,在超文本传输协议( Hypertext Transfer Protocol ,HTTP)的请求和响应消息中,协议头部分的那些组件.HTTP消息头用来准确描述正在获取的资源.服务器或 ...
- GO语言的进阶之路-Golang字符串处理以及文件操作
GO语言的进阶之路-Golang字符串处理以及文件操作 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 我们都知道Golang是一门强类型的语言,相比Python在处理一些并发问题也 ...
- 常用的HTTP请求头与响应头
HTTP消息头是指,在超文本传输协议( Hypertext Transfer Protocol ,HTTP)的请求和响应消息中,协议头部分的那些组件.HTTP消息头用来准确描述正在获取的资源.服务器或 ...
- golang常用库:cli命令行/应用程序生成工具-cobra使用
golang常用库:cli命令行/应用程序生成工具-cobra使用 一.Cobra 介绍 我前面有一篇文章介绍了配置文件解析库 Viper 的使用,这篇介绍 Cobra 的使用,你猜的没错,这 2 个 ...
- GOLANG 常用命令
golang常用命令: 命令 功能 build 编译包和依赖 run 编译并且直接运行 install 编译安装包和依赖 get 下载并安装包和依赖 fmt 调用gofmt格式化源码文件 d ...
- Win8开虚拟wifi ‘无法启动承载网络 组或资源的状态不是执行请求操作的正确状态“
第一步,首先我们点开开始按钮菜单,要右键以“管理员身份”打开CMD“命令提示符”并键入或者复制(粘贴)命令:netsh wlan show drivers 查看本机无线网卡是否支持此项Wifi热点共享 ...
- Shell基础:常用技巧&重定向&管道操作
Shell脚本介绍和常用工具 Shell脚本 Shell脚本:实际就是windows里的批处理脚本,多条可一次执行的Shell命令集合.Linux上的脚本可以用很多种语言实现,bash shell是比 ...
- C#常用工具类——Excel操作类
/// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...
随机推荐
- 使用Gitlab-CI 实现NetCore项目Docker化并部署到阿里云K8S
使用Gitlab-CI 实现NetCore项目Docker化并部署到阿里云K8S 先行条件: 1.了解NetCore项目基础命令,如dotnet publish 等几个常用命令. 2.了解Dock ...
- 【bfs】密码锁-C++
Description 现在一个紧急的任务是打开一个密码锁.密码由四位数字组成,每个数字从 1 到 9 进行编号.每次可以对任何数字加 1 或减 1.当将9加 1 时,数字将变为1,当1减 1 的时, ...
- python3.5学习笔记(第六章)
本章内容: 正则表达式详解(re模块) 1.不使用正则表达式来查找文本的内容 要求从一个字符串中查找电话号码,并判断是否匹配制定的模式,如:555-555-5555.传统的查找方法如下: def is ...
- UVA101 The Blocks Problem 题解
题目链接:https://www.luogu.org/problemnew/show/UVA101 这题码量稍有点大... 分析: 这道题模拟即可.因为考虑到所有的操作vector可最快捷的实现,所以 ...
- 【算法•日更•第十九期】动态规划:RMQ问题
▎前言 首先先来说一下RMB是什么,当然是人民币啦. 今天我们要学的这个东西不一般,叫做RMQ问题,那么它和RMB有什么关系呢?待小编细细说来. ▎前置技能:动态规划 不会的同志请戳这里迅速了解动态规 ...
- Linux系统安装Tomcat——.tar.gz版(old)
这里简单地阐述一下rpm.deb.tar.gz的区别. rpm格式的软件包适用于基于Red Hat发行版的系统,如Red Hat Linux.SUSE.Fedora. deb格式的软件包则是适用于基于 ...
- 2015.11.10 asn1学习笔记
Openssl : OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法.常用的密钥和证书封装管理功能及SSL协议,并提供丰富的应用程序供测试或其它目的使用. 在OpenSSL被曝出现严 ...
- C++多小球非对心弹性碰撞(HGE引擎)
程序是一个月前完成的,之前一直没正儿八经的来整理下这个程序,感觉比较简单,不过即使简单的东西也要跟大家分享下. 源码下载:http://download.csdn.net/detail/y851716 ...
- python基础——字符串(string)
字符串是 Python 中最常用的数据类型.我们可以使用引号('或")来创建字符串. 创建字符串很简单,只要为变量分配一个值即可. str1 = 'python' str2 = " ...
- session对象和cookie对象的区别
1.cookie数据存放在客户的浏览器上,session数据放在服务器上2.cookie不是很安全,别人可以分析存放在本地的COOKIE并进行COOKIE欺骗考虑到安全应当使用session3.ses ...