package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
var remoteUrl = "https://www.zhoubotong.site"
// 发送表单post请求
func postByForm() {
param := url.Values{}
param.Add("username", "乔峰")
param.Add("sex", "male")
resp, _ := http.PostForm(remoteUrl, param) // 表单提交"Content-Type": "application/x-www-form-urlencoded"
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
// 发送表单提交,可以对比上面的postByForm的实现差异
func postByForm2() {
urlValue := url.Values{
"username": {"乔峰"},
"sex": {"male"},
}
respData := urlValue.Encode()
fmt.Println(respData) // encode转码:name=%E4%B9%94%E5%B3%B0&sex=male
resp, _ := http.Post(remoteUrl, "text/html", strings.NewReader(respData))
//注意接收数据类型为text/html,对应在postman中的x-www-form-urlencoded中的key value参数
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
// 发送json数据
func postJson() {
client := &http.Client{Timeout: time.Second * 10}
param := make(map[string]interface{})
param["username"] = "乔峰"
param["sex"] = "male"
respdata, _ := json.Marshal(param) // respdata[]byte类型,转化成string类型便于查看
req, _ := http.NewRequest("POST", remoteUrl, bytes.NewReader(respdata))
//http.NewRequest请求会自动发送header中的Content-Type为applcation/json,对应在postman中的body的raw的json参数
resp, _ := client.Do(req)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
// 发送json数据,注意和上面实现的区别
func postJson2() {
param := make(map[string]interface{})
param["username"] = "乔峰"
param["sex"] = "male"
respdata, _ := json.Marshal(param) // respdata[]byte类型,转化成string类型便于查看
fmt.Println(string(respdata))
resp, _ := http.Post(remoteUrl, "application/json", bytes.NewReader(respdata))
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
/*
对应的postman中params中的key value参数,我估计很多人都很迷惑postman工具的params和body两个地方传递参数的区别,
其实Params处设置的变量请求时会url后问号传参(?x=y)。而Body里设置的参数则是接口真正请求时发的参数,下面这个例子就是通过params传参
*/
func postString() {
param := url.Values{}
param.Add("username", "babala")
param.Add("sex", "female")
u, _ := url.ParseRequestURI(remoteUrl)
u.RawQuery = param.Encode()
fmt.Println(u)
client := &http.Client{}
req, _ := http.NewRequest("POST", u.String(), nil) // 注意发送数据类似为string的post请求,对应的postman中params中的key value参数
resp, _ := client.Do(req)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
func main() {
//postByForm()
//postByForm2()
//postJson()
//postJson2()
postString()
}
通过上面的示例介绍,涉及了日常开发中各种场景的请求类型,基本满足了常规开发,以上只是示例,后端如何处理数据,大家可以自行解析