hpds_jkw_web/pkg/minedata/httpUtils.go

52 lines
1.1 KiB
Go
Raw Normal View History

2023-01-11 18:05:29 +08:00
package minedata
import (
2023-01-13 11:26:39 +08:00
"crypto/tls"
2023-01-11 18:05:29 +08:00
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
func HttpDo(reqUrl, method string, params map[string]string, header map[string]string) (data []byte, err error) {
var paramStr = ""
for k, v := range params {
if len(paramStr) == 0 {
paramStr = fmt.Sprintf("%s=%s", k, url.QueryEscape(v))
} else {
paramStr = fmt.Sprintf("%s&%s=%s", paramStr, k, url.QueryEscape(v))
}
}
2023-01-13 11:26:39 +08:00
client := &http.Client{
Transport: &http.Transport{ //对客户端进行一些配置
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
2023-01-11 18:05:29 +08:00
}
2023-01-13 11:26:39 +08:00
var req *http.Request
if strings.ToUpper(method) == "GET" {
reqUrl += "?" + paramStr
req, err = http.NewRequest(strings.ToUpper(method), reqUrl, nil)
} else {
req, err = http.NewRequest(strings.ToUpper(method), reqUrl, strings.NewReader(paramStr))
}
2023-01-11 18:05:29 +08:00
req.Header.Set("content-type", "X-WWW-FORM-URLENCODED")
for k, v := range header {
req.Header.Set(k, v)
}
resp, err := client.Do(req)
defer func() {
_ = resp.Body.Close()
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}