golang要請(qǐng)求遠(yuǎn)程網(wǎng)頁(yè),可以使用net/http包中的client提供的方法實(shí)現(xiàn)。查看了官方網(wǎng)站有一些示例,沒(méi)有太全面的例子,于是自己整理了一下:
創(chuàng)新互聯(lián)從2013年開(kāi)始,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元溫嶺做網(wǎng)站,已為上家服務(wù),為溫嶺各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:18982081108
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ù)無(wú)法傳遞。
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)單,這里就不再說(shuō)明。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
文章題目:golang使用httpclient發(fā)起get和post請(qǐng)求示例
本文網(wǎng)址:http://jinyejixie.com/article46/pocihg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、定制開(kāi)發(fā)、手機(jī)網(wǎng)站建設(shè)、品牌網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、用戶體驗(yàn)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)