使用Go的POST失败,但可以使用curl

使用Go的POST失败,但可以使用curl,curl,go,gorequest,Curl,Go,Gorequest,我已经针对我的应用程序测试了以下curl命令,它成功返回: curl --data "username=john&password=acwr6414" http://127.0.0.1:5000/api/login 然而,尝试在go中复制上述内容已被证明是一个相当大的挑战,我不断从服务器收到400个错误请求,下面是代码: type Creds struct { Username string `json:"username"` Password

我已经针对我的应用程序测试了以下curl命令,它成功返回:

curl --data "username=john&password=acwr6414" http://127.0.0.1:5000/api/login
然而,尝试在go中复制上述内容已被证明是一个相当大的挑战,我不断从服务器收到400个错误请求,下面是代码:

    type Creds struct {
        Username string `json:"username"`
        Password string `json:"password"`
    }

user := "john"
pass := "acwr6414"

    creds := Creds{Username: user, Password: pass}
    res, err := goreq.Request{
        Method:    "POST",
        Uri:       "http://127.0.0.1:5000/api/login",
        Body:      creds,
        ShowDebug: true,
    }.Do()
    fmt.Println(res.Body.ToString())
    fmt.Println(res, err)
我正在使用goreq软件包,我已经尝试了至少3或4个其他软件包,没有任何区别。我得到的错误是:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

您发送的是一个带有Go代码的json主体,但发送的是带有curl的application/x-www-form-urlencoded主体

您可以像使用curl一样手动编码字符串:

Body:      "password=acwr6414&user=john",
也可以使用url.Values对正文进行正确编码:

creds := url.Values{}
creds.Set("user", "john")
creds.Set("password", "acwr6414")

res, err := goreq.Request{
    ContentType: "application/x-www-form-urlencoded",
    Method:      "POST",
    Uri:         "http://127.0.0.1:5000/api/login",
    Body:        creds.Encode(),
    ShowDebug:   true,
}.Do()

您发送的是一个带有Go代码的json主体,但发送的是带有curl的application/x-www-form-urlencoded主体

您可以像使用curl一样手动编码字符串:

Body:      "password=acwr6414&user=john",
也可以使用url.Values对正文进行正确编码:

creds := url.Values{}
creds.Set("user", "john")
creds.Set("password", "acwr6414")

res, err := goreq.Request{
    ContentType: "application/x-www-form-urlencoded",
    Method:      "POST",
    Uri:         "http://127.0.0.1:5000/api/login",
    Body:        creds.Encode(),
    ShowDebug:   true,
}.Do()