使用标准库http中的Post方法来发送POST请求
func Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
bodyType即请求头信息中的Content-Type字段的内容
一个简单的示例代码,post请求httpbin.org/get这个页面,返回请求的一些信息
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
func main() {
url := "http://httpbin.org/post"
fmt.Printf("url: %s\n", url)
res, err := http.Post(
url,
"application/x-www-form-urlencoded",
strings.NewReader("name=nail"))
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", body)
}
运行结果:
url: http://httpbin.org/post
{
"args": {},
"data": "",
"files": {},
"form": {
"name": "nail"
},
"headers": {
"Accept-Encoding": "gzip",
"Connection": "close",
"Content-Length": "9",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Go-http-client/1.1"
},
"json": null,
"origin": "139.159.214.194",
"url": "http://httpbin.org/post"
}