Files
servicebase/pkg/common/HyTools/HttpClient.go
2025-11-18 17:48:20 +08:00

97 lines
1.6 KiB
Go

package HyTools
import (
"io/ioutil"
"net/http"
"strings"
)
// 调用POST请求
func HttpPost(url string, body string) (remoteResponse string, err error) {
bodyReader := strings.NewReader(body)
//application/x-www-form-urlencoded
//application/json
response, err1 := http.Post(url, "application/x-www-form-urlencoded", bodyReader)
if err1 != nil {
err = err1
return
}
defer response.Body.Close()
resBody, err2 := ioutil.ReadAll(response.Body)
if err2 != nil {
err = err2
return
}
remoteResponse = string(resBody)
return
}
// 复杂http请求
func HttpDo(httpMethod string, url string, headerMap map[string]string, rawBody string) (remoteResponse string, err error) {
client := &http.Client{}
req, err0 := http.NewRequest(httpMethod, url, strings.NewReader(rawBody))
if err0 != nil {
err = err0
return
}
if len(headerMap) > 0 {
for k, v := range headerMap {
req.Header.Set(k, v)
}
}
resp, err1 := client.Do(req)
if err1 != nil {
err = err1
return
}
defer resp.Body.Close()
body, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
err = err2
return
}
remoteResponse = string(body)
return
}
func HttpPostJson(url string, body string) (remoteResponse string, err error) {
bodyReader := strings.NewReader(body)
//application/x-www-form-urlencoded
//application/json
response, err1 := http.Post(url, "application/json", bodyReader)
if err1 != nil {
err = err1
return
}
defer response.Body.Close()
resBody, err2 := ioutil.ReadAll(response.Body)
if err2 != nil {
err = err2
return
}
remoteResponse = string(resBody)
return
}