func HttpGet(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
// handle error
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
return nil, err
}
return body, err
}
func HttpPostForm(queryUrl string, queryData map[string]string) ([]byte, error) {
// )
if len(queryData) == 0 || queryUrl == "" {
return nil, errors.New("参数错误")
}
url.Parse(queryUrl)
urlValue := url.Values{}
for k, v := range queryData {
var valList = make([]string, 1)
valList[0] = v
urlValue[k] = valList
}
resp, err := http.PostForm(queryUrl, urlValue)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
func HttpPostJson(queryUrl string, queryData map[string]string) ([]byte, error) {
if len(queryData) == 0 || queryUrl == "" {
return nil, errors.New("参数错误")
}
jsonStr, err := json.Marshal(queryData)
if err != nil {
return nil, errors.New("json编码出错")
}
// jsonStr := []byte()
req, err := http.NewRequest("POST", queryUrl, bytes.NewBuffer([]byte(jsonStr)))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
有疑问加站长微信联系(非本文作者)