Golang HTTP GET POST請求

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
package mainimport (    "fmt"    "io/ioutil"    "net/http"    "os"    "strings")func GET() {    client := &http.Client{}    reqest, err := http.NewRequest("GET", "http://www.baidu.com/", nil) //建立一個請求    if err != nil {        fmt.Println("Fatal error ", err.Error())        os.Exit(0)    }    //Add 頭協議    reqest.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")    reqest.Header.Add("Accept-Language", "ja,zh-CN;q=0.8,zh;q=0.6")    reqest.Header.Add("Connection", "keep-alive")    reqest.Header.Add("Cookie", "設定cookie")    reqest.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0")    response, err := client.Do(reqest) //提交    defer response.Body.Close()    cookies := response.Cookies() //遍曆cookies    for _, cookie := range cookies {        fmt.Println("cookie:", cookie)    }    body, err1 := ioutil.ReadAll(response.Body)    if err1 != nil {        // handle error    }    fmt.Println(string(body)) //網頁源碼}func post() {    client := &http.Client{}    req, err := http.NewRequest("POST", "http://xxxxx", strings.NewReader("name=1&age=2"))    if err != nil {        // handle error    }    reqest.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")    reqest.Header.Add("Accept-Language", "ja,zh-CN;q=0.8,zh;q=0.6")    reqest.Header.Add("Connection", "keep-alive")    reqest.Header.Add("Cookie", "設定cookie")    reqest.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0")    resp, err := client.Do(req)    cookies := resp.Cookies()    for _, cookie := range cookies {        fmt.Println("cookie:", cookie)    }    defer resp.Body.Close()    _, err1 := ioutil.ReadAll(resp.Body)    if err1 != nil {        // handle error    }    fmt.Println(string(body))}func main() {    GET()}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.