英文:
POST with Go fails but works with curl
问题
我已经测试了以下的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>
英文:
I've tested the following curl command against my app, and it returns successfully:
curl --data "username=john&password=acwr6414" http://127.0.0.1:5000/api/login
However trying to replicate the above in go has proven quite a challenge, I keep getting a 400 Bad Request error from the server, here's the code:
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)
I'm using the goreq package, I've tried at least 3 or 4 other packages with no difference. The error I get is:
<!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>
答案1
得分: 7
你的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()
英文:
You're sending a json body with your Go code, but an application/x-www-form-urlencoded
body with curl.
You can encode the string manually as you've done with curl:
Body: "password=acwr6414&user=john",
Or you can use a url.Values
to properly encode the body:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论