如何通过POST发送参数

use*_*588 1 post go

资源接收参数

例子: http://example.com/show-data?json={"fob":"bar"}

在 GET 请求的情况下,一切都清楚并且运行良好。

urlStr := "http://87.236.22.7:1488/test/show-data"
json := `"foo":"bar"`
r, _ := http.Get(urlStr+`?json=`+json)
println(r.Status)


200 OK
Run Code Online (Sandbox Code Playgroud)

但是在使用 POST 请求时应该怎么做呢?

我试试

 urlStr := "http://87.236.22.7:1488/test/show-data"
    json := `{"foo":"bar"}`
    form := url.Values{}
    form.Set("json", json)

    println(form.Encode())
    post, _ := http.PostForm(urlStr, form)

    println(post.Status)



400 Bad Request 

json parameter is missing
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

BJ *_*ack 5

有很多 POST 方法,但您可能想使用 PostForm:https ://golang.org/pkg/net/http/#PostForm

您需要先设置一个 Values 对象,然后将其直接传入。请参阅文档中的示例代码:https : //golang.org/pkg/net/url/#Values

将 json 塞入 Values 对象后,只需调用 PostForm() 即可启动它。

编辑:假设接收端想要一些编码为 application/x-www-form-urlencoded 的东西。如果接收端期待应用程序/json,我将提供第二个答案。