|
我想向 API 发出 POST 请求,以我的数据为数据application/x-www-form-urlencoded发送内容类型。因为我需要管理标头,所以我使用它http.NewRequest(method,urlStr string,body io.Reader)方法创建请求。POST 请求,我将我的数据查询附加到 URL 并将文本留空,如下所示:% Y" u- S; N: I
package mainimport "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(" OST",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)}7 `# y* }& u# P, |4 M/ l
当我回应时,我总是得到400 BAD REQUEST. 我相信问题取决于我的要求, API 不知道我发布的有效负载。我知道 这样的方法Request.ParseForm,但我不确定如何在这种情况下使用它。也许我错过了一些进一步的标题,也许有更好的方法application/json使用body以有效负载为类型发送参数?) }- k6 n! S) o
, J) q* V: p: g+ f4 [
解决方案:
0 q+ E5 g& e* U* k/ K 必须body在http.NewRequest(method,urlStr string,body io.Reader) 提供方法参数URL 作为实现编码的有效负载io.Reader接口类型。
: [# G4 B c+ b0 a# o, ]* c基于示例代码:
" o9 O& E5 K# Z `" [" D) npackage main
2 k$ j9 m+ G! [import (8 O& R0 ]4 f/ O5 P2 Y" O
“fmt”
5 _# u7 U. g6 Z" s( B “net/http”
* g( }9 V a P2 i. ? “net/url”
2 t; O$ k' K2 e* u. m “strconv”
9 [% G/ H' Z% V7 @1 c" b6 r “strings”
7 G* E$ k9 [$ f( G$ P5 l. Y6 M)
8 t* x$ s9 x- n Q0 i" i( tfunc main() {) E1 W- U) w5 s) W
apiUrl := "https://api.com“
, X- A8 J, W5 \( \0 S# |2 Q- y# y resource := “/user/”
) s. c' b1 m) r4 c! q5 h data := url.Values{}
' T/ c+ }3 C$ t& u) N( _7 g data.Set(“name”,“foo”)) z. I* r$ O% W
data.Set(“surname”,“bar”)
& P- J, U( y* V# ]3 B6 ru,_ := url.ParseRequestURI(apiUrl)u.Path = resourceurlStr := u.String() // "https://api.com/user/"client := &http.Client{}r,_ := http.NewRequest(http.MethodPost,urlStr,strings.NewReader(data.Encode()) // URL-encoded payloadr.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)}8 a( Y2 Z- x; M6 d2 c6 ?7 p& [, @
resp.Status是200 OK这样吗。 |
|