2015-11-06 88 views
1

我想送POST要求一起去,用捲曲的請求如下:去發送帖子要求?

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,錯在哪有了這個?

+1

你忽略了每一個可能的錯誤,也許你應該檢查他們。 – mrd0ll4r

+0

@ mrd0ll4r你是什麼意思? – roger

+0

@ mrd0ll4r我認爲問題出在我的請求數據上 – roger

回答

4

的請求主體是不一樣的:

在嫋嫋,你送{"inputs": [{"desc":"program","ind":"14","p":"program"}]}

在旅途中,你送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

0

你不需要設置「Content-Length」,而是我認爲你需要設置「host」屬性。

+0

and resp,err:= http.PostForm(「http://example.com/form」, \t url.Values {「key」:{「Value」},「id」:{「123」}}) –