golang的各种请求方法实现

1. GET请求

func httpGet() {
	resp, err := http.Get("http://www.baidu.com")
	if err != nil {
		// handle error
		fmt.Println(err.Error())
	}
	defer resp.body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
		fmt.Println(err.Error())
	}
	fmt.Println(string(body))
}

2. post请求

1. http.Post方式

func httpPost() {
	// 使用这个方法的话,第二个参数要设置成”application/x-www-form-urlencoded”,否则post参数无法传递。
	resp, err := http.Post("127.0.0.1:8080/user/login",
		"application/x-www-form-urlencoded",
		strings.NewReader("name=zhangsan"))
	if err != nil {
		fmt.Println(err.Error())
	} else {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			// handle error
			fmt.Println(err.Error())
		}
		fmt.Println(string(body))
	}
}

2. http.PostForm方法

func httpPostForm() {
	resp, err := http.PostForm("127.0.0.1:8080/user/login",
		url.Values{"name": {"zhangsan"}, "password": {"123456"}})
	if err != nil {
		fmt.Println(err.Error())
	} else {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			// handle error
			fmt.Println(err.Error())
		}
		fmt.Println(string(body))
	}
}

3. 比较复杂的请求,http.Do方法

//有时需要在请求的时候设置头参数、cookie之类的数据,就可以使用http.Do方法。

1. 使用strings.NewReader()传参
func httpDo(name string, password string) {
	client := &http.Client{}
	// 设置请求体
	data := url.Values{}
	// key,value必须为字符串类型
	data.Add("name", name)
	data.Add("password", password)
	// 请求中三个参数依次为 请求方法, 请求url, 请求体
	req, err := http.NewRequest("POST", "127.0.0.1:8080/user/login", strings.NewReader(data.Encode()))
	if err != nil {
		// handle error
	}
	// 设置请求头
	//必须要设定Content-Type为application/x-www-form-urlencoded,post参数才可正常传递
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := client.Do(req)
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
	}

	fmt.Println(string(body))
}
2. 使用bytes.NewBuffer()传参

// url:请求地址,data:POST请求提交的数据,contentType:请求体格式,如:application/json

func Post(url string, data interface{}, contentType string) string {
	jsonStr, _ := json.Marshal(data)
	req, err := http.NewRequest(`POST`, url, bytes.NewBuffer(jsonStr))
	req.Header.Add(`content-type`, contentType)
	if err != nil {
		panic(err)
	}
	defer req.Body.Close()
	// 设置超时时间
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	result, _ := ioutil.ReadAll(resp.Body)
	return string(result)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值