golang几种post请求方式
golang的net/http包既可以实现http server服务,也可以通过该包向http服务器发送post或get等模式的请求。上次总结过一篇 golang post和get发送请求 ,本篇基于上一篇做一些更细节场景的总结。
一、直接get请求
get请求可以直接http.Get方法,非常简单。
1func httpGet() {
2 resp, err := http.Get("https://blog.361way.com/demo/accept.php?id=1")
3 if err != nil {
4 // handle error
5 }
6 defer resp.Body.Close()
7 body, err := ioutil.ReadAll(resp.Body)
8 if err != nil {
9 // handle error
10 }
11 fmt.Println(string(body))
12}
二、直接post请求
方法1:
使用http.Post方式。使用这个方法的话,第二个参数要设置成”application/x-www-form-urlencoded”,否则post参数无法传递:
1func httpPost() {
2 resp, err := http.Post("https://blog.361way.com/demo/accept.php",
3 "application/x-www-form-urlencoded",
4 strings.NewReader("name=cjb"))
5 if err != nil {
6 fmt.Println(err)
7 }
8 defer resp.Body.Close()
9 body, err := ioutil.ReadAll(resp.Body)
10 if err != nil {
11 // handle error
12 }
13 fmt.Println(string(body))
14}
方法2:
也可以使用http.PostForm方法:
1func httpPostForm() {
2 resp, err := http.PostForm("https://blog.361way.com/demo/accept.php",
3 url.Values{"key": {"Value"}, "id": {"123"}})
4 if err != nil {
5 // handle error
6 }
7 defer resp.Body.Close()
8 body, err := ioutil.ReadAll(resp.Body)
9 if err != nil {
10 // handle error
11 }
12 fmt.Println(string(body))
13}
三、增加请求头信息
有时需要在请求的时候设置头参数、cookie之类的数据,就可以使用http.Do方法。
1func httpDo() {
2 client := &http.Client{}
3 req, err := http.NewRequest("POST", "https://blog.361way.com/demo/accept.php", strings.NewReader("name=cjb"))
4 if err != nil {
5 // handle error
6 }
7 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
8 req.Header.Set("Cookie", "name=anny")
9 resp, err := client.Do(req)
10 defer resp.Body.Close()
11 body, err := ioutil.ReadAll(resp.Body)
12 if err != nil {
13 // handle error
14 }
15 fmt.Println(string(body))
16}
同上面的post请求,必须要设定Content-Type为application/x-www-form-urlencoded,post参数才可正常传递。而对于比较简单的发起head请求可以直接使用http client的head方法。
四、根据http请求的类型
1.普通的post\get请求
1var r http.Request
2 r.ParseForm()
3 r.Form.Add("uuid", orderUUID)
4 bodystr := strings.TrimSpace(r.Form.Encode())
5 request, err := http.NewRequest("GET", url, strings.NewReader(bodystr))
6 if err != nil {
7 //TODO:
8 }
9 request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
10 request.Header.Set("Connection", "Keep-Alive")
11 var resp *http.Response
12 resp, err = http.DefaultClient.Do(request)
13 if err != nil {
14 //TODO:
15 }
2、body全部二进制数据流进行post
1//body提交二进制数据
2func DoBytesPost(url string, data []byte) ([]byte, error) {
3 body := bytes.NewReader(data)
4 request, err := http.NewRequest(POST_METHOD, url, body)
5 if err != nil {
6 log.Println("http.NewRequest,[err=%s][url=%s]", err, url)
7 return []byte(""), err
8 }
9 request.Header.Set("Connection", "Keep-Alive")
10 var resp *http.Response
11 resp, err = http.DefaultClient.Do(request)
12 if err != nil {
13 log.Println("http.Do failed,[err=%s][url=%s]", err, url)
14 return []byte(""), err
15 }
16 defer resp.Body.Close()
17 b, err := ioutil.ReadAll(resp.Body)
18 if err != nil {
19 log.Println("http.Do failed,[err=%s][url=%s]", err, url)
20 }
21 return b, err
22}
3、模拟web表单文件上传进行post
1func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
2 file, err := os.Open(path)
3 if err != nil {
4 return nil, err
5 }
6 defer file.Close()
7 body := &bytes.Buffer{}
8 writer := multipart.NewWriter(body)
9 part, err := writer.CreateFormFile(paramName, path)
10 if err != nil {
11 return nil, err
12 }
13 _, err = io.Copy(part, file)
14 for key, val := range params {
15 _ = writer.WriteField(key, val)
16 }
17 err = writer.Close()
18 if err != nil {
19 return nil, err
20 }
21 request, err := http.NewRequest("POST", uri, body)
22 request.Header.Set("Content-Type", writer.FormDataContentType())
23 return request, err
24}
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/go-post-data/6020.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.