简体   繁体   中英

Go send post request?

I want to send POST request with Go, the request with curl is as follow:

curl 'http://192.168.1.50:18088/' -d '{"inputs": [{"desc":"program","ind":"14","p":"program"}]}'

I do this with Go like this:

jobCateUrl := "http://192.168.1.50:18088/"

data := url.Values{}
queryMap := map[string]string{"p": "program", "ind": "14", "desc": "program"}
q, _ := json.Marshal(queryMap)
data.Add("inputs", string(q))

client := &http.Client{}
r, _ := http.NewRequest("POST", jobCateUrl, strings.NewReader(data.Encode()))
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

resp, _ := client.Do(r)
fmt.Println(resp)

but I failed, got 500 error , what wrong with this?

The Request bodies are not the same:

In curl, you send {"inputs": [{"desc":"program","ind":"14","p":"program"}]}

In go, you send inputs=%7B%22desc%22%3A%22program%22%2C%22ind%22%3A%2214%22%2C%22p%22%3A%22program%22%7D which URLDecodes to inputs={"desc":"program","ind":"14","p":"program"} .

So, what you should probably do is something like this:

type body struct {
    Inputs []input `json:"input"`
}

type input struct {
    Desc string `json:"desc"`
    Ind  string `json:"ind"`
    P    string `json:"p"`
}

Then create a body :

b := body{
    Inputs: []input{
        {
            Desc: "program",
            Ind:  "14",
            P:    "program"},
        },
}

Encode that:

q, err := json.Marshal(b)
if err != nil {
    panic(err)
}

You should obviously not panic, this is just for demonstration. Anyways, a string(q) will get you {"input":[{"desc":"program","ind":"14","p":"program"}]} .

Try it on the Playground

您不需要设置“ Content-Length”,相反,我认为您需要设置“ host”属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM