Go 发送http请求

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

func errCheck(err error) {
	if err != nil {
		panic(err)
	}
}

func printBody(r *http.Response) {
	body, _ := ioutil.ReadAll(r.Body)
	fmt.Println(string(body))
}

// 发送Get请求
func get() {
	request, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get", nil)
	errCheck(err)
	params := make(url.Values)
	params.Add("name", "Marshmallow")
	params.Add("age", "18")
	// fmt.Println(params.Encode()) // 这个可以自己打印下,其实就是age=18&name=Marshmallow
	request.URL.RawQuery = params.Encode()
	r, err := http.DefaultClient.Do(request)
	errCheck(err)
	defer func() { _ = r.Body.Close() }()
	printBody(r)

}

// 发送Post请求
func post() {
	request, err := http.NewRequest(http.MethodPost, "http://httpbin.org/post", nil)
	errCheck(err)
	r, err := http.DefaultClient.Do(request)
	errCheck(err)
	defer func() { _ = r.Body.Close() }()
	printBody(r)
}

// 发送Put请求
func put() {
	request, err := http.NewRequest(http.MethodPut, "http://httpbin.org/put", nil)
	errCheck(err)
	r, err := http.DefaultClient.Do(request)
	errCheck(err)
	defer func() { _ = r.Body.Close() }()
	printBody(r)
}

// 发送Delete请求
func del() {
	request, err := http.NewRequest(http.MethodDelete, "http://httpbin.org/delete", nil)
	errCheck(err)
	r, err := http.DefaultClient.Do(request)
	errCheck(err)
	defer func() { _ = r.Body.Close() }()
	printBody(r)
}

func main() {
	get()
	post()
	put()
	del()
}


Go 发送http请求

上一篇:js 防抖节流


下一篇:jmeter添加了json提取器,无法查看结果树