去发送post请求?

我想POST用 Go发送请求,使用 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 error,明白了,这有什么问题?


暮色呼如
浏览 133回答 2
2回答

素胚勾勒不出你

请求主体不一样:在 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哪些 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"}]}。在操场上试一试

HUX布斯

您不需要设置“内容长度”,而是我认为您需要设置“主机”属性。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go