golang使用http client發(fā)起get和post請(qǐng)求示例
golang要請(qǐng)求遠(yuǎn)程網(wǎng)頁(yè),可以使用net/http包中的client提供的方法實(shí)現(xiàn)。查看了官方網(wǎng)站有一些示例,沒有太全面的例子,于是自己整理了一下:
get請(qǐng)求
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請(qǐng)求
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))
}
Tips:使用這個(gè)方法的話,第二個(gè)參數(shù)要設(shè)置成”application/x-www-form-urlencoded”,否則post參數(shù)無法傳遞。
http.PostForm方法
func httpPostForm() {
resp, err := http.PostForm("http://www.01happy.com/demo/accept.php",
url.Values{"key": {"Value"}, "id": {"123"}})
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
復(fù)雜的請(qǐng)求
有時(shí)需要在請(qǐng)求的時(shí)候設(shè)置頭參數(shù)、cookie之類的數(shù)據(jù),就可以使用http.Do方法。
func httpDo() {
client := &http.Client{}
req, err := http.NewRequest("POST", "http://www.01happy.com/demo/accept.php", strings.NewReader("name=cjb"))
if err != nil {
// handle error
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Cookie", "name=anny")
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
同上面的post請(qǐng)求,必須要設(shè)定Content-Type為application/x-www-form-urlencoded,post參數(shù)才可正常傳遞。
如果要發(fā)起head請(qǐng)求可以直接使用http client的head方法,比較簡(jiǎn)單,這里就不再說明。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
go語(yǔ)言標(biāo)準(zhǔn)庫(kù)fmt包的一鍵入門
這篇文章主要為大家介紹了go語(yǔ)言標(biāo)準(zhǔn)庫(kù)fmt包的一鍵入門使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
Go語(yǔ)言實(shí)現(xiàn)操作MySQL的基礎(chǔ)知識(shí)總結(jié)
這篇文章主要總結(jié)一下怎么使用Go語(yǔ)言操作MySql數(shù)據(jù)庫(kù),文中的示例代碼講解詳細(xì),需要的朋友可以參考以下內(nèi)容,希望對(duì)大家有所幫助2022-09-09
Go實(shí)現(xiàn)生產(chǎn)隨機(jī)密碼的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用Go實(shí)現(xiàn)生產(chǎn)隨機(jī)密碼的,文中的示例代碼簡(jiǎn)潔易懂,具有一定的借鑒價(jià)值,有需要的小伙伴可以參考一下2023-09-09
Golang定時(shí)器Timer與Ticker的使用詳解
在 Go 里有很多種定時(shí)器的使用方法,像常規(guī)的 Timer、Ticker 對(duì)象,本文主要為大家介紹了Timer與Ticker的使用,感興趣的小伙伴可以了解一下2023-05-05
Go?runtime?調(diào)度器之系統(tǒng)調(diào)用引起的搶占
本文解析了在Go語(yǔ)言中,當(dāng)goroutine執(zhí)行的系統(tǒng)調(diào)用時(shí)間過長(zhǎng)時(shí),系統(tǒng)如何通過監(jiān)控和搶占機(jī)制來處理,以維持運(yùn)行效率和資源分配的平衡,通過具體的示例和流程圖,詳細(xì)展示了系統(tǒng)調(diào)用過程中的搶占操作,感興趣的朋友跟隨小編一起看看吧2024-09-09

