Skip to main content

从 URL 发起 HTTP 请求

基础说明

yak 原生的 http 是 Golang Native http 的高度封装,两者的内部对象并无大的差别。

使用 http 基础库#

rsp, err = http.Get("http://baidu.com")die(err)
# 获取 StatusCodeprintf("StatusCode: %v\n", rsp.StatusCode)
# 获取一个 Headerprintf("Content-Length: %v\n", rsp.Header["Content-Length"])
# 生成完整数据包rspRaw, err = http.dump(rsp)die(err)
println(string(rspRaw))
http.show(rsp.Request)

执行上述代码运行结果为

StatusCode: 200Content-Length: [81]HTTP/1.1 200 OKConnection: closeContent-Length: 81Accept-Ranges: bytesCache-Control: max-age=86400Content-Type: text/htmlDate: Sun, 27 Feb 2022 04:26:32 GMTEtag: "51-47cf7e6ee8400"Expires: Mon, 28 Feb 2022 04:26:32 GMTLast-Modified: Tue, 12 Jan 2010 13:48:00 GMTServer: Apache
<html><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></html>
GET / HTTP/1.1Host: baidu.com
补充说明

Yak 中的 http 模块本质上是对 Golang 原生 http 模块的高度封装。

返回的对象 *http.Response 和 Golang 的对象并无差别。用户随时都可以使用 desc(rsp) 查看详细对象成员

参数设置#

rsp, err = http.Get("http://127.0.0.1:3000/",                    http.proxy("http://127.0.0.1:8083"),        //http.proxy 设置代理                    http.ua(http.uarand()),                     //http.ua 设置user-agent、http.uarand获取一个随机的user-agent                    http.header("x-forward-for","127.0.0.1"),   //http.header设置一个header                    http.cookie("phpsession=abcdqwertyy"))      //http.cookie设置cookiedie(err)http.showhead(rsp) //http.showhead 打印出http的头部信息http.showhead(rsp.Request)

执行上述代码运行结果为

HTTP/1.1 200 OKConnection: closeTransfer-Encoding: chunkedAccept-Ranges: bytesAccess-Control-Allow-Origin: *Content-Encoding: gzipContent-Type: text/html; charset=UTF-8Date: Sun, 27 Feb 2022 04:48:52 GMTEtag: W/"63e-qSYRygpIfzO8dOVWWZ44nQMmFqA"Vary: Accept-EncodingX-Powered-By: Express

GET / HTTP/1.1Host: 127.0.0.1:3000Cookie: phpsession=abcdqwertyyUser-Agent: Mozilla/5.0 (X11; Linux i686; rv:49.0) Gecko/20100101 Firefox/49.0X-Forward-For: 127.0.0.1