HTTP的四种请求方法
生活随笔
收集整理的這篇文章主要介紹了
HTTP的四种请求方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
golang中net/http包提供了http相關操作的封裝,其中get方法和post方法進行的進一步的封裝,使用起來更加方便,其他的請求方式需要我們自己調用底層實現
package mainimport ("fmt""io/ioutil""net/http" )func get(){resp, err := http.Get("http://httpbin.org/get")if err != nil {panic(err)}defer func() {_ = resp.Body.Close()}()content, err := ioutil.ReadAll(resp.Body)if err != nil {panic(err)}fmt.Printf("%s", content)//{// "args": {},// "headers": {// "Accept-Encoding": "gzip",// "Host": "httpbin.org",// "User-Agent": "Go-http-client/1.1",// "X-Amzn-Trace-Id": "Root=1-60e4663e-4a475772249555e35a89632c"//},// "origin": "222.211.214.252",// "url": "http://httpbin.org/get"//} }func post(){resp, err := http.Post("http://httpbin.org/post", "", nil)if err != nil {panic(err)}defer func() {_ = resp.Body.Close()}()content, err := ioutil.ReadAll(resp.Body)if err != nil {panic(err)}fmt.Printf("%s", content)//{// "args": {},// "data": "",// "files": {},// "form": {},// "headers": {// "Accept-Encoding": "gzip",// "Content-Length": "0",// "Host": "httpbin.org",// "User-Agent": "Go-http-client/1.1",// "X-Amzn-Trace-Id": "Root=1-60e466bc-19f2a05e219847055d72f159"//},// "json": null,// "origin": "222.211.214.252",// "url": "http://httpbin.org/post"//} }func put(){request, err := http.NewRequest(http.MethodPut, "http://httpbin.org/put", nil)if err != nil {panic(err)}resp, err := http.DefaultClient.Do(request)if err != nil {panic(err)}defer func() {_ = resp.Body.Close()}()content, err := ioutil.ReadAll(resp.Body)if err != nil {panic(err)}fmt.Printf("%s", content)//{// "args": {},// "data": "",// "files": {},// "form": {},// "headers": {// "Accept-Encoding": "gzip",// "Content-Length": "0",// "Host": "httpbin.org",// "User-Agent": "Go-http-client/1.1",// "X-Amzn-Trace-Id": "Root=1-60e467e5-4db5430f5a0aa8ea75f5f805"//},// "json": null,// "origin": "222.211.214.252",// "url": "http://httpbin.org/put"//} }func delete(){request, err := http.NewRequest(http.MethodDelete, "http://httpbin.org/delete", nil)if err != nil {panic(err)}resp, err := http.DefaultClient.Do(request)if err != nil {panic(err)}defer func() {_ = resp.Body.Close()}()content, err := ioutil.ReadAll(resp.Body)if err != nil {panic(err)}fmt.Printf("%s", content)//{// "args": {},// "data": "",// "files": {},// "form": {},// "headers": {// "Accept-Encoding": "gzip",// "Host": "httpbin.org",// "User-Agent": "Go-http-client/1.1",// "X-Amzn-Trace-Id": "Root=1-60e4683b-6e4e08c400343a9f29a735fe"//},// "json": null,// "origin": "222.211.214.252",// "url": "http://httpbin.org/delete"//} }func main(){get()post()put()delete() }總結
以上是生活随笔為你收集整理的HTTP的四种请求方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构--快速排序
- 下一篇: HTTP中request请求参数的设置