Featured image of post Golang发送post请求

Golang发送post请求

使用golang发送post请求

准备http服务器

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
        if r.Method == "POST" {
            var (
                fmt.println(r.PostFormValue("key"))
            )
        }
    })

    _ := http.ListenAndServe(":1134", nil)
}

发送post请求

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
  data := url.Values{}
  data.Set("key", "Hello World!!")
  client := &http.Client{}
  r, _ := http.NewRequest("POST", "http://127.0.0.1:1134/test", strings.NewReader(data.Encode())) // URL-encoded payload
  r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
  resp, err := client.Do(r)
  if err != nil {
      fmt.Println(err.Error())
      return
  }
  defer resp.Body.Close()
}
Built with Hugo
Theme Stack designed by Jimmy