一.get 请求
func getRequest(url string) string{
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
result, _ := ioutil.ReadAll(resp.Body)
return string(result)
}
注:当get参数需要传入中文的时候,参数要进行转码,然后再拼接到url后
import (
"net/url"
)
param := url.QueryEscape(name)
requestUrl := "http://192.168.1.1/test?name=" + param
二.post 请求
func postRequest(url string, data interface{}, contentType string) string {
client := &http.Client{Timeout: 5 * time.Second}
jsonStr, _ := json.Marshal(data)
resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
if err != nil {
panic(err)
}
defer resp.Body.Close()
result, _ := ioutil.ReadAll(resp.Body)
return string(result)
}