Golang Httprequest
- 安装:
- 发送请求
- 自定义Transport
- Post 请求
- 传递URL参数
- 响应内容
- Json响应内容
- 定制请求头
- BasicAuth 认证
- CookieJar
- Proxy代理
- JSON请求
- Cookie
- 超时
- 关闭证书验证
- 调试模式
- 连接操作
- Respone对象
- 实例代码
Go语言HttpRequest项目源码地址: https://github.com/kirinlabs/HttpRequest
主要实现功能
-
支持常用的GET、POST、DELETE、PUT等
-
GET 除了正常请求url,也可以附带"name=flyfreely&address=beijing"或者map[string]interface{} 两种参数,包会自动整合到QueryString中
-
POST 支持string, []byte, *bytes.Reader, *bytes.Buffer, *strings.Reader, map[string]interface{}等参数; 如果发送JSON请求,几乎可以支持发送所有数据类型。
-
支持自定义Transport
具有快速构建Headers、Cookies、设置超时时间、请求、耗时、打印请求信息等功能
安装:
1go get https://github.com/kirinlabs/HttpRequest
发送请求
导入HttpRequest
1import "github.com/kirinlabs/HttpRequest"
实例化:
1req := HttpRequest.NewRequest()
然后,尝试获取某个网页。我们来获取 Github 的公共时间线
1res,err := req.Get("https://api.github.com/events")
返回一个res的Response对象和err的Error对象
自定义Transport
1var transport *http.Transport
2
3func init() {
4 transport = &http.Transport{
5 DialContext: (&net.Dialer{
6 Timeout: 30 * time.Second,
7 KeepAlive: 30 * time.Second,
8 DualStack: true,
9 }).DialContext,
10 MaxIdleConns: 100,
11 IdleConnTimeout: 90 * time.Second,
12 TLSHandshakeTimeout: 5 * time.Second,
13 ExpectContinueTimeout: 1 * time.Second,
14 }
15}
16
17func demo(){
18 // Use http.DefaultTransport
19 res, err := HttpRequest.Get("http://127.0.0.1:8080")
20
21 // Use custom Transport
22 res, err := HttpRequest.Transport(transport).Get("http://127.0.0.1:8080")
23}
Post 请求
1//无参请求
2res,err := req.Post("https://www.baidu.com")
3
4//发送整数类型
5res,err := req.Post("https://www.baidu.com",uint32(100))
6
7//发送[]byte
8res,err := req.Post("https://www.baidu.com",[]byte("bytes data"))
9
10//发送*bytes.Reader,*strings.Reader,*bytes.Buffer
11data := bytes.NewReader(buf []byte)
12res,err := req.Post("https://www.baidu.com",data)
13res,err := req.Post("https://www.baidu.com",strings.NewReader("string data"))
14
15//请求体为文本
16res,err := req.Post("https://www.baidu.com","hello")
17
18
19//请求体为Json字符串
20res,err := req.Post("https://www.baidu.com","{\"name\":\"github\"}")
21
22
23//map传参
24res.err := req.Post("https://www.baidu.com",map[string]interface{}{
25 "name":"github",
26 "type":1,
27})
也可以不用实例化,直接发送请求
1//快速发送Get请求
2res,err := HttpRequest.Get("https://www.baidu.com")
3
4res,err := HttpRequest.Get("https://www.baidu.com","title=baidu")
5
6
7//快速发送Post请求
8res,err := HttpRequest.Post("https://www.baidu.com")
9
10//发送整数类型
11res,err := req.Post("https://www.baidu.com",uint32(100))
12
13//发送[]byte
14res,err := req.Post("https://www.baidu.com",[]byte("bytes data"))
15
16//发送*bytes.Reader,*strings.Reader,*bytes.Buffer
17res,err := req.Post("https://www.baidu.com",bytes.NewReader(buf []byte))
18res,err := req.Post("https://www.baidu.com",bytes.NewBuffer(buf []byte))
19res,err := req.Post("https://www.baidu.com",strings.NewReader("string data"))
20
21
22res,err := HttpRequest.Post("https://www.baidu.com","title=baidu&type=pdf")
23
24res,err := HttpRequest.Post("https://www.baidu.com",map[string]interface{}{
25 "title":"baidu",
26})
27
28
29//快速发送JSON请求
30res,err := HttpRequest.JSON().Post("https://www.baidu.com",map[string]interface{}{
31 "title":"baidu",
32})
33
34res,err := HttpRequest.JSON().Post("https://www.baidu.com",`{"title":"baidu","type":"pdf"}`)
传递URL参数
你想为URL的查询字符串(query string)传递数据。如:手工构建URL,http://www.baidu.com/index?key=value。HttpRequest允许你使用第2个参数以字符串"id=100&name=github"或map[string]interface{}{“id”:10,“name”:“github”}字典的形式把数据传递给URL:
手工传参:
1res,err := req.Get("https://www.baidu.com/index?name=github")
字符串传参:
1res,err := req.Get("https://www.baidu.com/index?name=github","id=100&type=1")
map传参:
1res,err := req.Get("https://www.baidu.com/index?name=github",map[string]interface{}{
2 "id":10,
3 "type":1,
4})
响应内容
能读取服务器响应的内容
1res,err := req.Post("https://api.github.com/events")
获取服务器返回的内容:
1body,err := res.Body()
2
3fmt.Println(string(body))
获取服务器响应状态码:
1res.StatusCode()
获取服务器响应Headers:
1res.Headers()
返回一个map[string]string的字典
获取请求响应时间:
1res.Time()
Json响应内容
HttpRequest内置JSON解码,来解析JSON数据:
1//Format the json return value
2body, err := res.Json()
3
4fmt.Println(body)
如果JSON解码失败,会返回一个err错误
定制请求头
如果想为请求添加HTTP头部信息,只需要简单的传一个map给SetHeaders方法
1req.SetHeaders(map[string]string{
2 "Content-Type":"application/json",
3 "Source":"api",
4})
注:所有header值必须是字符串,SetHeaders可以多次调用,如果Key重复则会覆盖前面设置的值
BasicAuth 认证
如果想为请求添加HTTP头部信息,只需要简单的传一个map给SetHeaders方法
1req.SetBasicAuth("username","password")
CookieJar
1j, _ := cookiejar.New(nil)
2j.SetCookies(&url.URL{
3 Scheme: "http",
4 Host: "127.0.0.1:8000",
5}, []*http.Cookie{
6 &http.Cookie{Name: "identity-user", Value: "83df5154d0ed31d166f5c54ddc"},
7 &http.Cookie{Name: "token_id", Value: "JSb99d0e7d809610186813583b4f802a37b99d"},
8})
9res, err := HttpRequest.Jar(j).Get("http://127.0.0.1:8000/city/list")
10defer res.Close()
11if err != nil {
12 log.Fatalf("Request error:%v", err.Error())
13}
Proxy代理
通过代理Ip访问
1proxy, err := url.Parse("http://proxyip:proxyport")
2if err != nil {
3 log.Println(err)
4}
5
6res, err := HttpRequest.Proxy(http.ProxyURL(proxy)).Get("http://127.0.0.1:8000/ip")
7defer res.Close()
8if err != nil {
9 log.Println("Request error:%v", err.Error())
10}
11body, err := res.Body()
12if err != nil {
13 log.Println("Get body error:%v", err.Error())
14}
15log.Println(string(body))
JSON请求
如果想以json方式发送请求,HttpRequest支持2种方式
设置Header头部信息
1req.SetHeaders(map[string]string{"Content-Type":"application/json"})
2
3req.Post("https://www.baidu.com","{\"name\":\"github\"}")
调用req.JSON()内置方法
1//直接发磅Json字符串参数
2res,err := req.JSON().Post("https://www.baidu.com","{\"name\":\"github\"}")
3
4//自动将Map以Json方式发送参数
5res,err := req.JSON().Post("https://www.baidu.com",map[string]interface{}{
6 "name":"github"
7})
Cookie
1req.SetCookies(map[string]string{
2 "name":"jason"
3})
超时
1req.SetTimeout(5)
关闭证书验证
当请求https协议时提示x509: certificate signed by unknown authority时,可关闭证书验证
1 req.SetTLSClient(&tls.Config{InsecureSkipVerify: true})
调试模式
1req.Debug(true)
连接操作
而且还支持连接操作
1req := HttpRequest.NewRequest().Debug(true).SetTimeout(5).SetHeader()
Respone对象
获取返回的Response对象
1resp.Response()
获取返回码
1resp.StatusCode()
获取Body主体信息
1resp.Body()
返回[]byte和error
获取请求耗时
1resp.Time() string 单位是毫秒
获取真实Url
res.Url()
实例代码
1package main
2
3import (
4 "github.com/kirinlabs/HttpRequest"
5 "fmt"
6 "log"
7)
8
9func main() {
10
11 req := HttpRequest.NewRequest()
12
13 // 设置超时时间,不设置时,默认30s
14 req.SetTimeout(5)
15
16 // 设置Headers
17 req.SetHeaders(map[string]string{
18 "Content-Type": "application/x-www-form-urlencoded", //这也是HttpRequest包的默认设置
19 })
20
21 // 设置Cookies
22 req.SetCookies(map[string]string{
23 "sessionid": "LSIE89SFLKGHHASLC9EETFBVNOPOXNM",
24 })
25
26 postData := map[string]interface{}{
27 "id": 1,
28 "title": "csdn",
29 }
30
31 // GET 默认调用方法
32 resp, err := req.Get("http://127.0.0.1:8000?name=flyfreely")
33
34 // GET 传参调用方法
35 // 第2个参数默认为nil,也可以传参map[string]interface{}
36 // 第2个参数不为nil时,会把传入的map以query传参的形式重新构造新url
37 // 新的URL: http://127.0.0.1:8000?name=flyfreely&id=1&title=csdn
38
39 //resp, err := req.Get("http://127.0.0.1:8000?name=flyfreely", postData)
40
41 // POST 调用方法
42
43 //resp, err := req.Post("http://127.0.0.1:8000", postData)
44
45 if err != nil {
46 log.Println(err)
47 return
48 }
49
50 if resp.StatusCode() == 200 {
51 body, err := resp.Body()
52
53 if err != nil {
54 log.Println(err)
55 return
56 }
57
58 fmt.Println(string(body))
59 }
60
61 或者打印Json
62 if resp.StatusCode() == 200 {
63 body, err := resp.Json()
64
65 if err != nil {
66 log.Println(err)
67 return
68 }
69
70 fmt.Println(body)
71 }
72}