1 Star 0 Fork 0

liujinsuo/tool
暂停

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
http_client.go 2.30 KB
一键复制 编辑 原始数据 按行查看 历史
liujinsuo 提交于 2022-08-19 20:17 +08:00 . 增加http client函数
package tool
import (
"errors"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
// HttpGet 请求 响应内容过大不建议使用此方法
func HttpGet(url string, header map[string]string) (int, []byte, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return 0, nil, err
}
for k, v := range header {
req.Header.Add(k, v) //请求类型
}
client := &http.Client{
Timeout: 10 * time.Second, //设置超时时间
}
resp, err := client.Do(req)
if err != nil {
return 0, nil, err
}
if resp != nil {
defer resp.Body.Close()
} else {
return 0, nil, errors.New("http.Request not is nil")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, nil, err
}
return resp.StatusCode, body, nil
}
// HttpPostForm 请求 响应内容过大不建议使用此方法
func HttpPostForm(url string, data url.Values, header map[string]string) (int, []byte, error) {
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(data.Encode()))
if err != nil {
return 0, nil, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
for k, v := range header {
req.Header.Add(k, v) //请求类型
}
client := &http.Client{
Timeout: 10 * time.Second, //设置超时时间
}
resp, err := client.Do(req)
if err != nil {
return 0, nil, err
}
if resp != nil {
defer resp.Body.Close()
} else {
return 0, nil, errors.New("http.Request not is nil")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, nil, err
}
return resp.StatusCode, body, nil
}
// HttpPostJson 请求 响应内容过大不建议使用此方法
func HttpPostJson(url string, bodyRaw string, header map[string]string) (int, []byte, error) {
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(bodyRaw))
if err != nil {
return 0, nil, err
}
req.Header.Add("Content-Type", "application/json")
for k, v := range header {
req.Header.Add(k, v) //请求类型
}
client := &http.Client{
Timeout: 10 * time.Second, //设置超时时间
}
resp, err := client.Do(req)
if err != nil {
return 0, nil, err
}
if resp != nil {
defer resp.Body.Close()
} else {
return 0, nil, errors.New("http.Request not is nil")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, nil, err
}
return resp.StatusCode, body, nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/liujinsuo/tool.git
git@gitee.com:liujinsuo/tool.git
liujinsuo
tool
tool
68eb72d9e930

搜索帮助