去发送邮件请求?

时间:2015-11-06 07:37:50

标签: post go

我想用Go发送POST请求,curl的请求如下:

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

我这样做就像这样:

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)

但是我失败了,得到了500 error,这有什么问题?

2 个答案:

答案 0 :(得分:3)

请求正文不一样:

在卷曲中,您发送{"inputs": [{"desc":"program","ind":"14","p":"program"}]}

在go中,您将inputs=%7B%22desc%22%3A%22program%22%2C%22ind%22%3A%2214%22%2C%22p%22%3A%22program%22%7D个URLDecodes发送到inputs={"desc":"program","ind":"14","p":"program"}

所以,你应该做的是这样的事情:

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

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

然后创建body

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

编码:

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

你显然不应该恐慌,这只是为了示范。无论如何,string(q)会得到{"input":[{"desc":"program","ind":"14","p":"program"}]}

Playground

上试试

答案 1 :(得分:0)

您不需要设置" Content-Length"而我认为您需要设置"主机"属性。