Go发起GET请求

基本的GET请求

//基本的GET请求
package main import (
"fmt"
"io/ioutil"
"net/http"
) func main() {
resp, err := http.Get("http://www.hao123.com")
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://www.baidu.com?name=Paul_Chan&age=26")
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://www.baidu.com")
if err != nil {
return
}
params.Set("name","Paul_Chan")
params.Set("age","26")
//如果参数中有中文参数,这个方法会进行URLEncode
Url.RawQuery = params.Encode()
urlPath := Url.String()
fmt.Println(urlPath) // https://www.baidu.com?age=26&name=Paul_chan
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://xxx.com")
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://xxx.com",nil)
req.Header.Add("name","Paul_Chan")
req.Header.Add("age","26")
resp,_ := client.Do(req)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf(string(body))
}

从上述的结果可以看出我们设置的头是成功了:

{
"args": {},
"headers": {
"Accept-Encoding": "gzip",
"Age": "26",
"Host": "xxx.com",
"Name": "Paul_Chan",
"User-Agent": "Go-http-client/1.1"
},
"origin": "211.138.20.170, 211.138.20.170",
"url": "https://xxx.com"
}

golang 发起POST请求

基本的POST使用

package main

import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
) func main() {
urlValues := url.Values{}
urlValues.Add("name","Paul_Chan")
urlValues.Add("age","26")
resp, _ := http.PostForm("http://xxx.com/post",urlValues)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
//结果如下:
/******************
{
"args": {},
"data": "",
"files": {},
"form": {
"age": "26",
"name": "Paul_Chan"
},
"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":{"Paul_Chan"},
"age":{"26"},
}
reqBody:= urlValues.Encode()
resp, _ := http.Post("http://xxx.com/post", "text/html",strings.NewReader(reqBody))
body,_:= ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
//结果如下:
/**************
{
"args": {},
"data": "age=26&name=Paul_Chan",
"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))
}

做任何事情,都要以创业的心态去干!

最新文章

  1. MySQL 远程连接(federated存储引擎)
  2. 启动mysql时显示:/tmp/mysql.sock 不存在的解决方法
  3. Android studio教程
  4. Linux系统中“动态库”和“静态库”那点事儿【转】
  5. HTML5入门5---HTML5控件元素
  6. Android Activity 生命周期详解
  7. JS 一个修改ul的小示例
  8. ONVIFclient搜索设备获取rtsp解决开发笔记(精华文章)
  9. 【PHP系列】PHP组件详解
  10. red hat 6.5 红帽企业Linux.6.5 yum This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register. 解决办法
  11. 一种轻便且灵活的js模板的思路
  12. 使用Spring Cloud搭建高可用服务注册中心
  13. [MicroPython]TPYBoard开发板DIY小型家庭气象站
  14. win10下搭建storm环境
  15. VS 2015 Android 环境设置
  16. July 10th, Week 29th Sunday, 2016
  17. 计算完成率 SQL
  18. oracle创建新的用户 创建序列 并生成自动自增
  19. HTML+纯JS制作音乐播放器
  20. Leetcode题库——8.字符串转为整数【##】

热门文章

  1. linux应用程序设计--GCC程序编译
  2. Scrum是脆弱的,不敏捷的
  3. 【字符串】P2084 进制转换-C++
  4. Oracle粗心大意总结篇
  5. Oracle:ORA-01219:database not open:queries allowed on fixed tables/views only
  6. Excel催化剂开源第22波-VSTO的帮助文档在哪里?
  7. LiteDB源码解析系列(3)索引原理详解
  8. Kafka学习(三)-------- Kafka核心之Cosumer
  9. css关于flex布局下不能实现text-overflow: ellipsis的解决办法
  10. markdown常用方法