之前用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请求操作的更多相关文章

  1. Golang: 常用的文件读写操作

    Go 语言提供了很多文件操作的支持,在不同场景下,有对应的处理方式,今天就来系统地梳理一下,几种常用的文件读写的形式. 一.读取文件内容 1.按字节读取文件 这种方式是以字节为单位来读取,相对底层一些 ...

  2. HTTP消息头(HTTP headers)-常用的HTTP请求头与响应头

    HTTP消息头是指,在超文本传输协议( Hypertext Transfer Protocol ,HTTP)的请求和响应消息中,协议头部分的那些组件.HTTP消息头用来准确描述正在获取的资源.服务器或 ...

  3. GO语言的进阶之路-Golang字符串处理以及文件操作

    GO语言的进阶之路-Golang字符串处理以及文件操作 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 我们都知道Golang是一门强类型的语言,相比Python在处理一些并发问题也 ...

  4. 常用的HTTP请求头与响应头

    HTTP消息头是指,在超文本传输协议( Hypertext Transfer Protocol ,HTTP)的请求和响应消息中,协议头部分的那些组件.HTTP消息头用来准确描述正在获取的资源.服务器或 ...

  5. golang常用库:cli命令行/应用程序生成工具-cobra使用

    golang常用库:cli命令行/应用程序生成工具-cobra使用 一.Cobra 介绍 我前面有一篇文章介绍了配置文件解析库 Viper 的使用,这篇介绍 Cobra 的使用,你猜的没错,这 2 个 ...

  6. GOLANG 常用命令

    golang常用命令: 命令 功能 build      编译包和依赖 run 编译并且直接运行 install 编译安装包和依赖 get 下载并安装包和依赖 fmt 调用gofmt格式化源码文件 d ...

  7. Win8开虚拟wifi ‘无法启动承载网络 组或资源的状态不是执行请求操作的正确状态“

    第一步,首先我们点开开始按钮菜单,要右键以“管理员身份”打开CMD“命令提示符”并键入或者复制(粘贴)命令:netsh wlan show drivers 查看本机无线网卡是否支持此项Wifi热点共享 ...

  8. Shell基础:常用技巧&重定向&管道操作

    Shell脚本介绍和常用工具 Shell脚本 Shell脚本:实际就是windows里的批处理脚本,多条可一次执行的Shell命令集合.Linux上的脚本可以用很多种语言实现,bash shell是比 ...

  9. C#常用工具类——Excel操作类

    /// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...

随机推荐

  1. 就是要让你彻底学会 @Bean 注解

    @Bean 注解全解析 随着SpringBoot的流行,基于注解式开发的热潮逐渐覆盖了基于XML纯配置的开发,而作为Spring中最核心的bean当然也能够使用注解的方式进行表示.所以本篇就来详细的讨 ...

  2. html解析器:Html Agility Pack

    去掉注释.样式.和js代码: foreach(var script in doc.DocumentNode.Descendants("script").ToArray()) scr ...

  3. Nginx+Lua+MySQL/Redis实现高性能动态网页展现

    Nginx结合Lua脚本,直接绕过Tomcat应用服务器,连接MySQL/Redis直接获取数据,再结合Lua中Template组件,直接写入动态数据,渲染成页面,响应前端,一次请求响应过程结束.最终 ...

  4. windows切换mac遇到的问题

    1. 前端代码需要安装npm包 所以需要对整个文件夹都赋予管理员权限 2. 在npm i的时候如果权限不足 查看是哪一行调用了哪个文件夹,赋予权限 3. Dsp-fe 本地环境 除了需要配置host  ...

  5. JAVA BIO,NIO,Reactor模式总结

    传统同步阻塞I/O(BIO) 在NIO之前编写服务器使用的是同步阻塞I/O(Blocking I/O).下面是一个典型的线程池客服端服务器示例代码,这段代码在连接数急剧上升的情况下,这个服务器代码就会 ...

  6. MyBatis 接口多参数的处理方法

    From<MyBatis从入门到精通> 1.接口类中增加的方法: /* 2.7 多个接口参数的用法 多个参数时,可以选取的方案有:使用Map类型或者使用@Param注解 使用Map类型作为 ...

  7. [记录]优化Linux 的内核参数来提高服务器并发处理能力

    优化Linux 的内核参数来提高服务器并发处理能力PS:在服务器硬件资源额定有限的情况下,最大的压榨服务器的性能,提高服务器的并发处理能力,是很多运维技术人员思考的问题.要提高Linux 系统下的负载 ...

  8. IQueryable.Where中动态生成多个并或筛选Expression<Func<T, bool>>

    直接上图

  9. 获取文件版本(IE)

    GetFileInfoCUIAction::GetFileVersion2GetSystemDirectory     WCHAR szConfigFile[MAX_PATH + 1];    ::G ...

  10. 洛谷P2001 硬币的面值 题解

    题目链接:https://www.luogu.org/problemnew/show/P2001 这题的数据范围吓得我很慌. 分析: 这道题蒟蒻本来想用背包的,但是发现m太大,一写肯定炸,然后看到数据 ...