【问题标题】:POST with Go fails but works with curlGo 的 POST 失败但适用于 curl
【发布时间】:2017-05-29 00:43:15
【问题描述】:

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

curl --data "username=john&password=acwr6414" http://127.0.0.1:5000/api/login

然而,尝试在 go 中复制上述内容已被证明是一个相当大的挑战,我不断收到来自服务器的 400 Bad Request 错误,代码如下:

    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>

【问题讨论】:

    标签: curl go gorequest


    【解决方案1】:

    您发送的是带有 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()
    

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 2022-01-03
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      相关资源
      最近更新 更多