"Transfer from http://www.01happy.com/golang-http-client-get-and-post/"
GET request
Get requests can be directly HTTP. The Get method is very simple.
1234567891011121314 |
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))
}
|
One of the post requests is to use HTTP. Post mode
12345678910111213141516 |
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: Using this method, the second parameter is set to "application/x-www-form-urlencoded", otherwise the post parameter cannot be passed.
One is to use HTTP. Postform method
1234567891011121314151617 |
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))
}
|
A complex request
Sometimes you need to set the header parameters, cookies and other data at the time of the request, you can use HTTP. Do method.
12345678910111213141516171819202122 |
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))
}
|
With the above POST request, you must set Content-type as the Application/x-www-form-urlencoded,post parameter to pass normally.
If you want to initiate a head request can be directly using the HTTP client head method, relatively simple, here is no longer explained.
Full code sample file download: Golang_http_client initiating get and post code samples
Golang example of Get and POST requests initiated using HTTP client