post - 去发送帖子请求吗?

标签 post go

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

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

我用 Go 这样做是这样的:

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错误,这有什么问题吗?

最佳答案

请求正文不同:

在curl中,您发送{"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,其 URL 解码为 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"`
}

然后创建一个正文:

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

编码:

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

您显然不应该 panic ,这只是为了演示。无论如何, string(q) 将为您提供 {"input":[{"desc":"program","ind":"14","p":"program"}]}

Playground 上尝试一下

关于post - 去发送帖子请求吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33561703/

相关文章:

javascript - 从具有多个变量的表单构建一个帖子数据结构

go - 如何使用 Go reflect 向 cron 添加功能?

mysql - 如何从 View 中 *sql.Rows 类型的变量中获取值?

c - Go cgo ldap_init 无法确定 C.ldap_init 的名称类型

ios - 如何使用 iOS 向 Twitter 好友发送直接消息

iphone - iPhone 应用程序的 POST REST-Web 服务调用

php - Android Volley POST 请求 : getting GET request method on server side (php)

swift - urlrequest不发送post请求

json - 在执行json解码后,输出为空,但未发生解析错误

mongodb - Golang、mongodb不能做select