我想对发送我的数据作为application/x-www-form-urlencoded
内容类型的API发出POST请求.由于我需要管理请求标头,我正在使用该http.NewRequest(method, urlStr string, body io.Reader)
方法来创建请求.对于此POST请求,我将我的数据查询附加到URL并将正文保留为空,如下所示:
package main
import (
"bytes"
"fmt"
"net/http"
"net/url"
"strconv"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Add("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
u.RawQuery = data.Encode()
urlStr := fmt.Sprintf("%v", u) // "https://api.com/user/?name=foo&surname=bar"
client := &http.Client{}
r, _ := http.NewRequest("POST", urlStr, nil)
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
Run Code Online (Sandbox Code Playgroud)
当我回答时,我总是得到一个400 BAD REQUEST
.我相信问题依赖于我的请求,API不了解我发布的有效负载.我知道方法Request.ParseForm
,但不确定如何在这种情况下使用它.也许我错过了一些更多的Header,也许是否有更好的方法application/json …