1、
package main
import (
"fmt"
"net/http"
"net/url"
"strings"
)
func main() {
url := "https://httpbin.org/post"
data := url.Values{}
data.Set("username", "user")
data.Set("password", "pass")
payload := strings.NewReader(data.Encode())
req, err := http.NewRequest("POST", url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("response Body:", string(body))
}
2、
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "http://example.com/path/to/api"
data := []byte("action=wpcom_load_posts&page=2&type=default&exclude=")
req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(body))
}