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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器