一、net/http的httpclient发起http请求
方法
- get请求
func httpGet() {
resp, err := http.Get("http://www.01happy.com/demo/accept.php?id=1")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
- post请求
- 方法一:http.Post方法
func httpPost() {
resp, err := http.Post("http://www.01happy.com/demo/accept.php",
"application/x-www-form-urlencoded",
strings.NewReader("name=cjb"))
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
使用这个方法,第二个参数(contentType)必须设置为"application/x-www-form-urlencoded",否则post参数无法传递
- 方法二:http.PostForm方法
func httpPostForm() {
resp, err := http.PostForm("http://www.01happy.com/demo/accept.php",
url.Values{
"key": {
"Value"}, "id": {
"123"}})
<

本文详细解析了Golang中net/http包的http客户端发起HTTP请求的流程,特别是Do/Get/Post方法的实现及Transport的RoundTrip方法。讲解了连接池的工作原理,包括如何获取TCP长连接以及如何在多个goroutine间复用持久连接。同时介绍了如何通过设置各种参数来精细化控制HTTP请求的行为,如超时和连接池管理。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



