博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
golang常用的http请求操作
阅读量:4958 次
发布时间:2019-06-12

本文共 5371 字,大约阅读时间需要 17 分钟。

之前用python写各种网络请求的时候写的非常顺手,但是当打算用golang写的时候才发现相对来说还是python的那种方式用的更加顺手,习惯golang的用法之后也就差别不大了,下面主要整理了常用的通过golang发起的GET请求以及POST请求的代码例子

golang发起GET请求

基本的GET请求

//基本的GET请求package mainimport (    "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 mainimport (    "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 mainimport (    "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 mainimport (    "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 mainimport (    "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 mainimport (    "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 mainimport (    "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 mainimport (    "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 mainimport (    "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/zhaof/p/11346412.html

你可能感兴趣的文章
Python模块调用
查看>>
委托的调用
查看>>
c#中从string数组转换到int数组
查看>>
数据模型(LP32 ILP32 LP64 LLP64 ILP64 )
查看>>
java小技巧
查看>>
POJ 3204 Ikki's Story I - Road Reconstruction
查看>>
【BZOJ】2959: 长跑(lct+缩点)(暂时弃坑)
查看>>
iOS 加载图片选择imageNamed 方法还是 imageWithContentsOfFile?
查看>>
toad for oracle中文显示乱码
查看>>
SQL中Group By的使用
查看>>
错误org/aopalliance/intercept/MethodInterceptor解决方法
查看>>
Pylint在项目中的使用
查看>>
使用nginx做反向代理和负载均衡效果图
查看>>
access remote libvirtd
查看>>
(4) Orchard 开发之 Page 的信息存在哪?
查看>>
ASP.NET中 GridView(网格视图)的使用前台绑定
查看>>
深入了解Oracle ASM(二):ASM File number 1 文件目录
查看>>
Boosting(提升方法)之AdaBoost
查看>>
链接元素<a>
查看>>
Binding object to winForm controller through VS2010 Designer(通过VS2010设计器将对象绑定到winForm控件上)...
查看>>