我想向API发出POST请求,将我的数据作为application/x-www-form-urlencoded
内容类型发送.由于我需要管理请求头,所以我使用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)
}
当我回答时,我总是得到400 BAD REQUEST
分.我相信问题取决于我的请求,而API不理解我发布的是哪个有效负载.我知道像Request.ParseForm
这样的方法,但是不太确定如何在这个上下文中使用它.也许我遗漏了更多的头,也许有更好的方式使用body
参数将有效负载作为application/json
类型发送?