HTTP中request请求参数的设置
生活随笔
收集整理的這篇文章主要介紹了
HTTP中request请求参数的设置
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在發送的http請求中我們可以定制自己的請求體,下面是幾個示例代碼
package mainimport ("fmt""io/ioutil""net/http""net/url" )func printBody(r *http.Response){content, err := ioutil.ReadAll(r.Body)if err != nil {panic(err)}fmt.Printf("%s", content) }//設置請求查詢參數 func requestByParams(){request, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get", nil)if err != nil {panic(err)}params := make(url.Values)params.Add("name", "yuan")params.Add("age", "18")request.URL.RawQuery = params.Encode()fmt.Println(params.Encode())resp, err := http.DefaultClient.Do(request)if err != nil {panic(err)}defer func() {_ = resp.Body.Close()}()printBody(resp)//{// "args": {// "age": "18",// "name": "yuan"//},// "headers": {// "Accept-Encoding": "gzip",// "Host": "httpbin.org",// "User-Agent": "Go-http-client/1.1",// "X-Amzn-Trace-Id": "Root=1-60e46b98-58667aee5367f1aa1ca102c9"//},// "origin": "222.211.214.252",// "url": "http://httpbin.org/get?age=18&name=yuan"//} }//定制請求頭 func reauestByHead(){request, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get", nil)if err != nil {panic(err)}request.Header.Add("user-agent", "chrome")resp, err := http.DefaultClient.Do(request)if err != nil {panic(err)}defer func() {_ = resp.Body.Close()}()printBody(resp)//{// "args": {},// "headers": {// "Accept-Encoding": "gzip",// "Host": "httpbin.org",// "User-Agent": "chrome",// "X-Amzn-Trace-Id": "Root=1-60e46c63-22fd52047229e6175f52166c"//},// "origin": "222.211.214.252",// "url": "http://httpbin.org/get"//} } func main() {requestByParams()reauestByHead() }總結
以上是生活随笔為你收集整理的HTTP中request请求参数的设置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTTP的四种请求方法
- 下一篇: HTTP中response响应数据获取