利用GO发起http请求(post and get)|Go主题月

3,944 阅读2分钟

需求

http请求:

  • 发起百度搜索的GET请求:www.baidu.com/s?wd=ReganY… ,打印回复的内容

  • httpbin.org/post 发起post请求,携带表单数据(application/x-www-form-urlencoded),建值自拟(strings.NewReader("money=0&hobby=撩妹")),打印回复的内容

  • 表单数据类型application/x-www-form-urlencoded,表单读取API:strings.NewReader("money=0&hobby=撩妹")

下面摆代码咯!

先是发起post请求的Go代码。

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

/*http请求:
· 发起百度搜索的GET请求:“http://www.baidu.com/s?wd=ReganYue”,打印回复的内容
· 对https://httpbin.org/post发起post请求,携带表单数据(application/x-www-form-urlencoded),建值自拟(strings.NewReader("money=0&hobby=撩妹")),打印回复的内容
· 表单数据类型application/x-www-form-urlencoded,表单读取API:strings.NewReader("money=0&hobby=撩妹")
*/
func main() {
	resp, err := http.Post("https://httpbin.org/post?name=Regan&money=0",
		"application/x-www-form-urlencoded",
		strings.NewReader("姓名=ReganYue&人民币=0&心愿=发财发财"))
	HandleError(err,"http.Post")

	defer resp.Body.Close()

	bytes, err := ioutil.ReadAll(resp.Body)
	HandleError(err,"ioutil.ReadAll")
	fmt.Println(string(bytes))
}
func HandleError(err error,when string) {
	if err != nil {
		fmt.Println(err,when)
		os.Exit(1)
	}
}

然后是发起Get请求的Go代码

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

/*http请求:
· 发起百度搜索的GET请求:“http://www.baidu.com/s?wd=ReganYue”,打印回复的内容
· 对https://httpbin.org/post发起post请求,携带表单数据(application/x-www-form-urlencoded),建值自拟(strings.NewReader("money=0&hobby=撩妹")),打印回复的内容
· 表单数据类型application/x-www-form-urlencoded,表单读取API:strings.NewReader("money=0&hobby=撩妹")
*/
func main() {
	resp, err := http.Get("http://www.baidu.com/s?wd=ReganYue")
	HandleError(err,"http.Get")

	defer resp.Body.Close()

	bytes, err := ioutil.ReadAll(resp.Body)
	HandleError(err,"ioutil.ReadAll")
	fmt.Println(string(bytes))

}

func HandleError(err error,when string) {
	if err != nil {
		fmt.Println(err,when)
		os.Exit(1)
	}
}

下面看一下返回的数据

先来看看Get请求的。

image.png

image.png

image.png

然后我们看看Post请求的。

给这个网站:httpbin.org 发请求,它会返回JSON包。

{
  "args": {
    "money": "0", 
    "name": "Regan"
  }, 
  "data": "", 
  "files": {}, 
  "form": {
    "\u4eba\u6c11\u5e01": "0", 
    "\u59d3\u540d": "ReganYue", 
    "\u5fc3\u613f": "\u53d1\u8d22\u53d1\u8d22"
  }, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Content-Length": "47", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Go-http-client/2.0", 
    "X-Amzn-Trace-Id": "Root=1-6065828e-4217f17c421b398523a6850a"
  }, 
  "json": null, 
  "origin": "", 
  "url": "https://httpbin.org/post?name=Regan&money=0"
}

args是get请求的参数:"money": "0", "name": "Regan"。

"form": {
    "\u4eba\u6c11\u5e01": "0", 
    "\u59d3\u540d": "ReganYue", 
    "\u5fc3\u613f": "\u53d1\u8d22\u53d1\u8d22"
  }, 

form是表单数据

headers是请求头。

"Accept-Encoding": "gzip"表明接受的编码gzip

"Content-Length": "47",数据的长度是47个字节

"origin": "",表示我的发起请求的ip是这个,此处我已经将ip数据删除。

"url": "https://httpbin.org/post?name=Regan&money=0"就是url地址。