英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论