Golang http請求封裝的代碼示例
1、POST請求
1.1、POST請求發(fā)送 json
這里發(fā)送json筆者使用了2種方式,一種是golang 自帶的 http.Post方法,另一是 http.NewRequest
方法。二者的區(qū)別是http.Post方法不能發(fā)送自定義的header數(shù)據(jù);而http.NewRequest方法可以發(fā)送額外的自定義header數(shù)據(jù)
先看使用golang 自帶的 http.Post方法封裝的POST請求
func HttpPostJson(url string, requestBody []byte) (string, error) { response, er := http.Post(url, "application/json", bytes.NewBuffer(requestBody)) if er != nil { return "", er } defer response.Body.Close() body, er2 := ioutil.ReadAll(response.Body) if er2 != nil { return "", er2 } return string(body), nil }
再看使用http.NewRequest方法封裝的POST請求
看golang的源代碼可以知道 http.Post方法底層就是使用的 NewRequest 方法,因此NewRequest方法更加靈活
func HttpPost(url string, header map[string]string, requestBody []byte) (string, error) { httpClient := &http.Client{} request, er := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(requestBody)) if er != nil { return "", er } for key, value := range header { request.Header.Set(key, value) } //設置請求頭Content-Type request.Header.Set("Content-Type", "application/json") response, er2 := httpClient.Do(request) if er2 != nil { return "", er2 } defer response.Body.Close() body, er3 := ioutil.ReadAll(response.Body) if er3 != nil { return "", er3 } return string(body), nil }
1.2、POST請求發(fā)送form
form數(shù)據(jù)使用map存放,map的key是字符串,value是字符串切片
func HttpPostForm(url string, form map[string][]string) (string, error) { response, er := http.PostForm(url, form) if er != nil { return "", er } defer response.Body.Close() body, er2 := ioutil.ReadAll(response.Body) if er2 != nil { return "", er2 } return string(body), nil }
可以攜帶自定義header的post請求發(fā)送form
筆者使用NewRequest 方法封裝的可以攜帶自定義header的form請求
func HttpPostHeaderForm(requestUrl string, header map[string]string, form map[string][]string) (string, error) { httpClient := &http.Client{} var data url.Values data = map[string][]string{} for k, v := range form { data[k] = v } request, er := http.NewRequest(http.MethodPost, requestUrl, strings.NewReader(data.Encode())) if er != nil { return "", er } request.Header.Set("Content-Type", "application/x-www-form-urlencoded") //設置自定義header for key, value := range header { request.Header.Set(key, value) } response, er := httpClient.Do(request) if er != nil { return "", er } defer response.Body.Close() body, er2 := ioutil.ReadAll(response.Body) if er2 != nil { return "", er2 } return string(body), nil }
2、GET請求
func HttpGet(url string) (string, error) { response, er := http.Get(url) if er != nil { return "", er } defer response.Body.Close() body, er2 := ioutil.ReadAll(response.Body) if er2 != nil { return "", er2 } return string(body), nil }
3、測試
這里服務端筆者使用springboot項目創(chuàng)建,用來接收請求,端口默認8080
參數(shù)類
package com.wsjz.demo.param; import lombok.Data; @Data public class AddParam { private String name; private Integer age; }
controller
package com.wsjz.demo.controller; import com.wsjz.demo.param.AddParam; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; @RestController public class DemoController { @PostMapping("/json/add") public String jsonAdd(@RequestBody AddParam param, HttpServletRequest request) { System.out.println(request.getHeader("token")); System.out.println(param); return "json ok"; } @PostMapping("/form/add") public String formAdd(AddParam param, HttpServletRequest request) { System.out.println(request.getHeader("token")); System.out.println(param); return "form ok"; } @GetMapping("/get/add") public String getAdd(AddParam param) { System.out.println(param); return "get ok"; } }
golang測試代碼
新建User結(jié)構(gòu)體做為參數(shù)
type User struct { Name string `json:"name"` Age int `json:"age"` }
(1)、測試HttpPostJson方法
func TestHttpPostJson(t *testing.T) { url := "http://localhost:8080/json/add" var user = User{ Name: "舉頭西北浮云,倚天萬里須長劍,人言此地,夜深長見,斗牛光焰", Age: 17, } requestBody, er := json.Marshal(user) if er != nil { log.Fatal(er) } response, er := HttpPostJson(url, requestBody) if er != nil { fmt.Println(er) } fmt.Println(response) }
運行效果
(2)、測試HttpPost方法
func TestHttpPost(t *testing.T) { url := "http://localhost:8080/json/add" var header = make(map[string]string) header["token"] = "2492dc007dfc4ce8adcc8b42b21641f4" var user = User{ Name: "我見青山多嫵媚", Age: 17, } requestBody, er := json.Marshal(user) if er != nil { log.Fatal(er) } response, er2 := HttpPost(url, header, requestBody) if er2 != nil { log.Fatal(er2) } fmt.Println(response) }
運行效果
(3)、測試HttpPostForm方法
func TestHttpPostForm(t *testing.T) { url := "http://localhost:8080/form/add" var form = make(map[string][]string) form["name"] = []string{"可憐今夕月,向何處,去悠悠"} form["age"] = []string{"18"} response, er := HttpPostForm(url, form) if er != nil { fmt.Println(er) } fmt.Println(response) }
運行效果
(4)、測試HttpPostHeaderForm方法
func TestHttpPostHeaderForm(t *testing.T) { url := "http://localhost:8080/form/add" var header = make(map[string]string) header["token"] = "0a8b903b7d7448e3ab007caab081965c" var form = make(map[string][]string) form["name"] = []string{"相思字,空盈幅,相思意,何時足"} form["age"] = []string{"18"} response, er := HttpPostHeaderForm(url, header, form) if er != nil { fmt.Println(er) } fmt.Println(response) }
運行效果
(5)、測試HttpGet方法
func TestHttpGet(t *testing.T) { //對中文進行編碼 name := url.QueryEscape("乘風好去,長空萬里,直下看山河") requestUrl := "http://localhost:8080/get/add?name=" + name + "&age=19" response, er := HttpGet(requestUrl) if er != nil { fmt.Println(er) } fmt.Println(response) }
運行效果
以上就是Golang http請求封裝的代碼示例的詳細內(nèi)容,更多關(guān)于Golang http請求封裝的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Golang時間處理庫go-carbon?v2.2.13發(fā)布細則
這篇文章主要為大家介紹了Golang?時間處理庫go-carbon?v2.2.13發(fā)布細則,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11Go語言入門教程之Arrays、Slices、Maps、Range操作簡明總結(jié)
這篇文章主要介紹了Go語言入門教程之Arrays、Slices、Maps、Range操作簡明總結(jié),本文直接給出操作代碼,同時對代碼加上了詳細注釋,需要的朋友可以參考下2014-11-11手把手教你vscode配置golang開發(fā)環(huán)境的步驟
這篇文章主要介紹了手把手教你vscode配置golang開發(fā)環(huán)境的步驟,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03