dsoihsnz85757 2017-01-13 15:31
浏览 193
已采纳

使用Go进行POST失败,但可以使用curl

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条回答 默认 最新

  • douba6365 2017-01-13 15:39
    关注

    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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法