Go语言之Golang http请求库HttpRequest

Go语言HttpRequest项目源码地址: https://github.com/kirinlabs/HttpRequest

主要实现功能

目录

安装:

发送请求

传递URL参数

响应内容

Json响应内容

定制请求头

BasicAuth 认证

CookieJar

Proxy代理

JSON请求

超时   

关闭证书验证

调试模式

连接操作

Respone对象

实例代码


具有快速构建HeadersCookies设置超时时间请求、耗时、打印请求信息等功能

安装:

go get https://github.com/kirinlabs/HttpRequest

发送请求

导入HttpRequest

import "github.com/kirinlabs/HttpRequest"

实例化:

req := HttpRequest.NewRequest()

然后,尝试获取某个网页。我们来获取 Github 的公共时间线

res,err := req.Get("https://api.github.com/events")

返回一个res的Response对象和err的Error对象

Post 请求

//无参请求
res,err := req.Post("https://www.baidu.com")


//请求体为文本
res,err := req.Post("https://www.baidu.com","hello")


//请求体为Json字符串
res,err := req.Post("https://www.baidu.com","{\"name\":\"github\"}")


//map传参
res.err := req.Post("https://www.baidu.com",map[string]interface{}{
    "name":"github",
    "type":1,
})

 也可以不用实例化直接发送请求

//快速发送Get请求
res,err := HttpRequest.Get("https://www.baidu.com")

res,err := HttpRequest.Get("https://www.baidu.com","title=baidu")


//快速发送Post请求
res,err := HttpRequest.Post("https://www.baidu.com")

res,err := HttpRequest.Post("https://www.baidu.com","title=baidu&type=pdf")

res,err := HttpRequest.Post("https://www.baidu.com",map[string]interface{}{
    "title":"baidu",
})


//快速发送JSON请求
res,err := HttpRequest.JSON().Post("https://www.baidu.com",map[string]interface{}{
    "title":"baidu",
})

res,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:

手工传参:

res,err := req.Get("https://www.baidu.com/index?name=github")

字符串传参:

res,err := req.Get("https://www.baidu.com/index?name=github","id=100&type=1")

map传参:

res,err := req.Get("https://www.baidu.com/index?name=github",map[string]interface{}{
    "id":10,
    "type":1,
})

 

响应内容

能读取服务器响应的内容

res,err := req.Post("https://api.github.com/events")

 获取服务器返回的内容:

body,err := res.Body()

fmt.Println(string(body))

获取服务器响应状态码:

res.StatusCode()

获取服务器响应Headers:

res.Headers()

返回一个map[string]string的字典

获取请求响应时间:

res.Time()

Json响应内容

HttpRequest内置JSON解码,来解析JSON数据:

//Format the json return value
body, err := res.Json() 

fmt.Println(body)

如果JSON解码失败,会返回一个err错误

 

定制请求头

如果想为请求添加HTTP头部信息,只需要简单的传一个map给SetHeaders方法

req.SetHeaders(map[string]string{
    "Content-Type":"application/json",
    "Source":"api",
})

注:所有header值必须是字符串,SetHeaders可以多次调用,如果Key重复则会覆盖前面设置的值

 

BasicAuth 认证

如果想为请求添加HTTP头部信息,只需要简单的传一个map给SetHeaders方法

req.SetBasicAuth("username","password")

CookieJar

j, _ := cookiejar.New(nil)
j.SetCookies(&url.URL{
	Scheme: "http",
	Host:   "127.0.0.1:8000",
}, []*http.Cookie{
	&http.Cookie{Name: "identity-user", Value: "83df5154d0ed31d166f5c54ddc"},
	&http.Cookie{Name: "token_id", Value: "JSb99d0e7d809610186813583b4f802a37b99d"},
})
res, err := HttpRequest.Jar(j).Get("http://127.0.0.1:8000/city/list")
defer res.Close()
if err != nil {
	log.Fatalf("Request error:%v", err.Error())
}

Proxy代理

通过代理Ip访问

proxy, err := url.Parse("http://proxyip:proxyport")
if err != nil {
	log.Println(err)
}

res, err := HttpRequest.Proxy(http.ProxyURL(proxy)).Get("http://127.0.0.1:8000/ip")
defer res.Close()
if err != nil {
	log.Println("Request error:%v", err.Error())
}
body, err := res.Body()
if err != nil {
	log.Println("Get body error:%v", err.Error())
}
log.Println(string(body))

 

JSON请求

如果想以json方式发送请求,HttpRequest支持2种方式

设置Header头部信息

req.SetHeaders(map[string]string{"Content-Type":"application/json"})

req.Post("https://www.baidu.com","{\"name\":\"github\"}")

调用req.JSON()内置方法

//直接发磅Json字符串参数
res,err := req.JSON().Post("https://www.baidu.com","{\"name\":\"github\"}")

//自动将Map以Json方式发送参数
res,err := req.JSON().Post("https://www.baidu.com",map[string]interface{}{
    "name":"github"
})
req.SetCookies(map[string]string{
    "name":"jason"
})

超时   

 req.SetTimeout(5)

关闭证书验证

当请求https协议时提示x509: certificate signed by unknown authority时,可关闭证书验证

 req.SetTLSClient(&tls.Config{InsecureSkipVerify: true})

调试模式

req.Debug(true)

连接操作

而且还支持连接操作

req := HttpRequest.NewRequest().Debug(true).SetTimeout(5).SetHeader()

Respone对象

获取返回的Response对象

resp.Response()

获取返回码

 resp.StatusCode()

获取Body主体信息   

resp.Body() 

 返回[]byte和error

获取请求耗时

resp.Time() string   单位是毫秒

获取真实Url

res.Url()

实例代码

package main

import (
   "github.com/kirinlabs/HttpRequest"
   "fmt"
   "log"
)

func main() {

   req := HttpRequest.NewRequest()

   // 设置超时时间,不设置时,默认30s
   req.SetTimeout(5)

   // 设置Headers
   req.SetHeaders(map[string]string{
      "Content-Type": "application/x-www-form-urlencoded", //这也是HttpRequest包的默认设置
   })

   // 设置Cookies
   req.SetCookies(map[string]string{
      "sessionid": "LSIE89SFLKGHHASLC9EETFBVNOPOXNM",
   })

   postData := map[string]interface{}{
      "id":    1,
      "title": "csdn",
   }

   // GET 默认调用方法
   resp, err := req.Get("http://127.0.0.1:8000?name=flyfreely")

   // GET 传参调用方法
   // 第2个参数默认为nil,也可以传参map[string]interface{}
   // 第2个参数不为nil时,会把传入的map以query传参的形式重新构造新url
   // 新的URL: http://127.0.0.1:8000?name=flyfreely&id=1&title=csdn

   //resp, err := req.Get("http://127.0.0.1:8000?name=flyfreely", postData)

   // POST 调用方法

   //resp, err := req.Post("http://127.0.0.1:8000", postData)

   if err != nil {
      log.Println(err)
      return
   }

   if resp.StatusCode() == 200 {
      body, err := resp.Body()
      
      if err != nil {
         log.Println(err)
         return
      }
      
      fmt.Println(string(body))
   }

   或者打印Json
   if resp.StatusCode() == 200 {
      body, err := resp.Json()
      
      if err != nil {
         log.Println(err)
         return
      }
      
      fmt.Println(body)
   }
}

 

你可能感兴趣的:(Go)