You are viewing an old version of this page. View the current version.
Compare with Current View Page History
Version 17 Current »
GoFrame框架提供了强大便捷易用的HTTP客户端,由gclient组件实现,对象创建可以通过gclient.New()包方法,也可以通过g.Client()方法调用。推荐使用g.Client()来便捷地创建HTTP客户端对象。由于gclient.Client内部封装扩展于标准库的http.Client对象,因此标准库http.Client有的特性,gclient.Client也是支持的。
GoFrame
HTTP
gclient
gclient.New()
g.Client()
gclient.Client
http.Client
方法列表: https://pkg.go.dev/github.com/gogf/gf/v2/net/gclient
简要说明:
New
Client
Close
HTTP Method
Get
Post
DoRequest
*ClientResponse
ReadAll
ReadAllString
*Bytes
nil
*Content
Set*
*Var
g.Var
data
interface{}
string
map
urlencode
请使用给定的方法创建Client对象,而不要使用new(ghttp.Client)或者&ghttp.Client{}创建客户端对象,否则,哼哼。
new(ghttp.Client)
&ghttp.Client{}
GoFrame框架的客户端支持便捷的链式操作,常用方法如下(文档方法列表可能滞后于源码,建议查看接口文档或源码 https://pkg.go.dev/github.com/gogf/gf/v2/net/gclient):
func (c *Client) Timeout(t time.Duration) *Client func (c *Client) Cookie(m map[string]string) *Client func (c *Client) Header(m map[string]string) *Client func (c *Client) HeaderRaw(headers string) *Client func (c *Client) ContentType(contentType string) *Client func (c *Client) ContentJson() *Client func (c *Client) ContentXml() *Client func (c *Client) BasicAuth(user, pass string) *Client func (c *Client) Retry(retryCount int, retryInterval time.Duration) *Client func (c *Client) Prefix(prefix string) *Client func (c *Client) Proxy(proxyURL string) *Client func (c *Client) RedirectLimit(redirectLimit int) *Client func (c *Client) Dump(dump ...bool) *Client func (c *Client) Use(handlers ...HandlerFunc) *Client
Timeout
Cookie
Header*
Header
Content*
Content-Type
BasicAuth
HTTP Basic Auth
Retry
Proxy
RedirectLimit
gclient.Response为HTTP对应请求的返回结果对象,该对象继承于http.Response,可以使用http.Response的所有方法。在此基础之上增加了以下几个方法:
gclient.Response
http.Response
func (r *Response) GetCookie(key string) string func (r *Response) GetCookieMap() map[string]string func (r *Response) Raw() string func (r *Response) RawDump() func (r *Response) RawRequest() string func (r *Response) RawResponse() string func (r *Response) ReadAll() []byte func (r *Response) ReadAllString() string func (r *Response) Close() error
这里也要提醒的是,Response需要手动调用Close方法关闭,也就是说,不管你使用不使用返回的Response对象,你都需要将该返回对象赋值给一个变量,并且手动调用其Close方法进行关闭(往往使用defer r.Close()),否则会造成文件句柄溢出、内存溢出。
Response
defer r.Close()
ghttp
KeepAlive
TLS
Transport
http.Transport