package httputil import ( "bytes" "crypto/tls" "fmt" "github.com/spf13/cast" "io" "net/http" "net/url" "time" ) func HttpPostForm(requestUrl string, header map[string]interface{}, forms map[string]interface{}) ([]byte, error) { client := &http.Client{Timeout: 20 * time.Second} client.Transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } values := url.Values{} if forms != nil { for k, v := range forms { values.Set(k, cast.ToString(v)) } } req, err := http.NewRequest("POST", requestUrl, bytes.NewBufferString(values.Encode())) if err != nil { return nil, err } if header != nil { for k, v := range header { req.Header.Set(k, cast.ToString(v)) } } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("%d:%s", resp.StatusCode, resp.Status) } return io.ReadAll(resp.Body) } // PostJson 请求 func HttpPostJson(link string, params map[string]interface{}, header map[string]interface{}, json []byte) ([]byte, error) { client := &http.Client{Timeout: 20 * time.Second} //忽略https的证书 client.Transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } p := url.Values{} u, _ := url.Parse(link) if params != nil { for k, v := range params { p.Set(k, cast.ToString(v)) } } u.RawQuery = p.Encode() req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(json)) if err != nil { return nil, err } req.Header.Add("Content-Type", "application/json") if header != nil { for k, v := range header { req.Header.Add(k, cast.ToString(v)) } } resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("%d:%s", resp.StatusCode, resp.Status) } return io.ReadAll(resp.Body) }