go语言http请求(一)

我们在开发的过程中多多少少会要跟其他服务做交互,很多都是http请求,但是在go语言里面怎么样请求http请求,今天先讲比较初级的。示例如下:

GET

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

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

post

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"strings"
)

func main(){
    client := &http.Client{}
    requst, err := http.NewRequest("POST", 
                                "http://www.baidu.com", 
                                strings.NewReader("name=abc"))
    if err != nil {
        return
    }
    requst.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    response, err := client.Do(requst)
    if err != nil {
        return
    }
    defer response.Body.Close()
    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        return
    }
    fmt.Println(string(body))
}

推荐文档:https://cloud.tencent.com/developer/section/1143633

猜你喜欢

转载自blog.csdn.net/zf766045962/article/details/89242601