first commit
This commit is contained in:
71
pkg/htools/HttpClient.go
Normal file
71
pkg/htools/HttpClient.go
Normal file
@ -0,0 +1,71 @@
|
||||
package htools
|
||||
|
||||
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
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user