如何通过POST发送参数

resource receives the parameters

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

in case of GET request, all clear and work well.

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


200 OK

But how it shoud be done when use POST request?

i try

 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

but it`s not work.

There are a bunch of ways to POST stuff, but you probably want to use PostForm: https://golang.org/pkg/net/http/#PostForm

You'll need to set up a Values object first then pass it right in. See the example code in the docs: https://golang.org/pkg/net/url/#Values

Once you've jammed the json into a Values object, just call PostForm() to fire it up.

Edit: This works assuming that the receiving end is wanting something encoded as application/x-www-form-urlencoded. I'm putting in a second answer if the receiving end is expecting application/json.

This answer assumes that the receiving end is expecting application/json. It's still problematic in this particular case, though I've verified using Wireshark that the request is correct (has the correct headers and body content):

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {

    // Create a key/value map of strings
    kvPairs := make(map[string]string)
    kvPairs["foo"] = "bar"

    // Make this JSON
    postJson, err := json.Marshal(kvPairs)
    if err != nil { panic(err) }
    fmt.Printf("Sending JSON string '%s'
", string(postJson))

    // http.POST expects an io.Reader, which a byte buffer does
    postContent := bytes.NewBuffer(postJson)

    // Send request to OP's web server
    resp, err := http.Post("http://87.236.22.7:1488/test/show-data", "application/json", postContent)
    if err != nil { panic(err) }

    // Spit back the complete status
    fmt.Printf("Status: %s
", resp.Status)
    buf, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(buf))
}

It appears that either the receiving yii framework doesn't know what to do with this type of REST request, or is expecting stuff in the GET part of the parameters anyway. The yii page describing REST requests has an example CURL command line that makes a request that's more like what the code above does, but it doesn't work in OP's example.

OP: Please double-check your receiver to make sure it's configured to receive such requests. A similar CURL command line should work (and if it does, so should my code).