golang使用http client發(fā)起get和post請求示例
golang要請求遠程網(wǎng)頁,可以使用net/http包中的client提供的方法實現(xiàn)。查看了官方網(wǎng)站有一些示例,沒有太全面的例子,于是自己整理了一下:
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)) }
Tips:使用這個方法的話,第二個參數(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ù)雜的請求
有時需要在請求的時候設(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請求,必須要設(shè)定Content-Type為application/x-www-form-urlencoded,post參數(shù)才可正常傳遞。
如果要發(fā)起head請求可以直接使用http client的head方法,比較簡單,這里就不再說明。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Go語言實現(xiàn)操作MySQL的基礎(chǔ)知識總結(jié)
這篇文章主要總結(jié)一下怎么使用Go語言操作MySql數(shù)據(jù)庫,文中的示例代碼講解詳細,需要的朋友可以參考以下內(nèi)容,希望對大家有所幫助2022-09-09Go?runtime?調(diào)度器之系統(tǒng)調(diào)用引起的搶占
本文解析了在Go語言中,當(dāng)goroutine執(zhí)行的系統(tǒng)調(diào)用時間過長時,系統(tǒng)如何通過監(jiān)控和搶占機制來處理,以維持運行效率和資源分配的平衡,通過具體的示例和流程圖,詳細展示了系統(tǒng)調(diào)用過程中的搶占操作,感興趣的朋友跟隨小編一起看看吧2024-09-09