方法一:
直接使用form传参,没有头参
/*
http请求
*/
func HttpPostRequest(urls string, datas map[string]string) string {
data := url.Values{}
for index := range datas {
data.Add(index, datas[index])
}
res, _ := http.PostForm(urls, data)
if res.StatusCode != 200 {
}
body, _ := ioutil.ReadAll(res.Body)
s := string(body)
fmt.Println(s)
}
方法二:
在请求的时候设置头参数、cookie之类的数据,就可以使用http.Do方法
注意:post请求,必须要设定Content-Type为application/x-www-form-urlencoded,post参数才可正常传递!
/*
http请求
在请求的时候设置头参数、cookie之类的数据,就可以使用http.Do方法
注意:post请求,必须要设定Content-Type为application/x-www-form-urlencoded,post参数才可正常传递!
*/
func HttpPostRequest(urls string, datas map[string]string, headers map[string]string) PostResponse {
var r http.Request
r.ParseForm()
for index := range datas {
r.Form.Add(index, datas[index])
}
bodyForm := strings.TrimSpace(r.Form.Encode()) //去除空的数据
fmt.Println(bodyForm)
//做连接请求,设置头hearder
client := &http.Client{}
request, err := http.NewRequest("POST", urls,strings.NewReader(bodyForm))//
request.Header.Set("Content-Type", "application/x-www-form-urlencoded") //必须要设置该头,否则传参postForm其实是个空结构
if len(headers) > 0 {
for index, value := range headers {
request.Header.Add(index, value)
}
}
if err != nil {
panic(err)
}
res, _ := client.Do(request)
if res.StatusCode != 200 {
}
body, _ := ioutil.ReadAll(res.Body)
s := string(body)
fmt.Println(s)
}