Reputation: 9933
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?
Upvotes: 2
Views: 246
Reputation: 886
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
Upvotes: 3
Reputation: 923
You don't need to set the "Content-Length", and instead i think you need to set the "host" attribute.
Upvotes: 0