Initiating an HTTP request in the Golang language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
<strong>//Simple Direct GET request </strong>func HttpGet () {resp, err: = http. Get ("http://www.baidu.com") if err! = Nil {//Handle error} Defer resp. Body.close () body, err: = Ioutil. ReadAll (resp. Body) If err! = Nil {//Handle error} FMT. Println (String)}<strong>//POST request--using HTTP. The Post () method </strong>func HttpPost () {resp, err: = http. Post ("http://www.baidu.com", "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 (body)}tips: Using this method, the second parameter is set to "application/x-www-form-urlencoded", otherwise the post parameter cannot be passed. <strong>//POST request--using HTTP. Postform () method </strong>func Httppostform () {resp, err: = http. Postform ("http://www.baidu.com", 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)}<strong>//complex requests (set header parameters, cookies, and so on) and can use HTTP. The Do () method of the client </strong>func Httpdo () {client: = &http. client{} req, err: = http. Newrequest ("POST", "http://www.baidu.com", 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))}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.