使用`http.NewRequest(…)`进行URL编码的POST请求。

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

Make a URL-encoded POST request using `http.NewRequest(...)`

问题

我想向一个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类型发送吗?

英文:

I want to make a POST request to an API sending my data as a application/x-www-form-urlencoded content type. Due to the fact that I need to manage the request headers, I'm using the http.NewRequest(method, urlStr string, body io.Reader) method to create a request. For this POST request I append my data query to the URL and leave the body empty, something like this:

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)
}

As I response, I get always a 400 BAD REQUEST. I believe the problem relies on my request and the API does not understand which payload I am posting. I'm aware of methods like Request.ParseForm, not really sure how to use it in this context though. Maybe am I missing some further Header, maybe is there a better way to send payload as a application/json type using the body parameter?

答案1

得分: 247

URL编码的有效载荷必须作为实现了io.Reader接口的类型,提供给http.NewRequest(method, urlStr string, body io.Reader)方法的body参数。

根据示例代码:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

这样,resp.Status将会是200 OK

英文:

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

huangapple
  • 本文由 发表于 2013年10月9日 00:38:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/19253469.html
匿名

发表评论

匿名网友

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

确定