如何同时发送URL参数和JSON主体的POST请求?

huangapple go评论103阅读模式
英文:

How te send a POST with both URL parameters and a JSON body?

问题

我找到了如何发送带有URL参数的POST请求,以及如何发送带有JSON主体的POST请求,但我不知道如何将它们组合在一起(即同时具有URL参数和JSON主体的请求)。

下面的代码(不正确)展示了我正在寻找的组合方式。我可以使用bytes.NewBuffer(jsonStr)strings.NewReader(parm.Encode())中的任何一个,但不能同时使用两者。

package main

import (
	"bytes"
	"net/http"
	"net/url"
	"strings"
)

func main() {
	var jsonStr = []byte(`{"title":"my request"}`)
	parm := url.Values{}
	parm.Add("token", "hello")
	req, err := http.NewRequest("POST", "https://postman-echo.com/post", bytes.NewBuffer(jsonStr), strings.NewReader(parm.Encode()))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

}

如何构建一个完整的POST请求,包括所有组件?

英文:

I found how to send a POST with URL parameters, or how to send a POST with a JSON body, but I do not know how to combine them together (a request with both a URL with parameters, and a JSON body).

The code below (which is not correct) shows the commbination I am looking for. I can use either bytes.NewBuffer(jsonStr) or strings.NewReader(parm.Encode()) but not both.

package main

import (
	"bytes"
	"net/http"
	"net/url"
	"strings"
)

func main() {
	var jsonStr = []byte(`{"title":"my request"}`)
	parm := url.Values{}
	parm.Add("token", "hello")
	req, err := http.NewRequest("POST", "https://postman-echo.com/post", bytes.NewBuffer(jsonStr), strings.NewReader(parm.Encode()))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

}

How to build a full POST call with all the components?

答案1

得分: 2

请使用仅包含 JSON 的请求正文,并按照以下方式应用 URL 参数:

req.URL.RawQuery = parm.Encode()

参考自 Go doing a GET request and building the Querystring

英文:

Use the only json as your request body, and apply the URL parameters like this:

req.URL.RawQuery = parm.Encode()

From Go doing a GET request and building the Querystring

huangapple
  • 本文由 发表于 2021年5月29日 15:55:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/67749056.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定