我需要发送一个数据对象,例如{hello: "world", goodbye: "world"}
到API。我现在正在这样做:
inputs := form.GetElementsByTagName("input")
var data = make(map[string]interface{}) // after adding values this looks like this: {hello: "world", goodbye: "world"}
for value := range inputs {
// Append all values from the inputs to a new array, with the key named by the input name attribute
if inputs[value] != nil && inputs[value].(*dom.HTMLInputElement).Value != "" {
data[inputs[value].(*dom.HTMLInputElement).Name] = inputs[value].(*dom.HTMLInputElement).Value
}
}
parsedData, _ := json.Marshal(data)
req, _ := http.NewRequest(method, url, bytes.NewBuffer(parsedData))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
go func() { // Must be a goroutine
response, _ := client.Do(req)
defer response.Body.Close()
}()
我遇到的问题是,因为我们将其作为字节发送,服务器总是返回错误响应,因为它期望处理一个对象。
如何确保它发送的是对象而不是字节?
答案 0 :(得分:3)
您正在以json格式发送数据时将内容类型设置为application/x-www-form-urlencoded
,因此在设置请求标头时请更改内容类型,并且不要跳过该错误以检查内容是什么。返回错误:
parsedData, err := json.Marshal(data)
if err != nil{
fmt.Println(err)
}
req, err := http.NewRequest(method, url, parsedData) // send the parseData which are bytes returned from the marshal.
if err != nil{
fmt.Println(err)
}
req.Header.Set("Content-Type", "application/json") // set the content type to json
go func() { // Must be a goroutine
response, err := client.Do(req)
if err != nil{
fmt.Println(err)
}
defer response.Body.Close()
}()
// you should check for response status to verify the details as
fmt.Println("response Status:", response.Status)
fmt.Println("response Headers:", response.Header)
body, _ := ioutil.ReadAll(response.Body)
fmt.Println("response Body:", string(body))
应考虑的一件事是您尚未导出结构字段。这可能是您的json字符串为空的原因。通过使每个字段的首字母大写,使结构字段可导出。
答案 1 :(得分:0)
我使用"net/url"
软件包解决了这个问题。
data := url.Values{}
for value := range inputs {
// Append all values from the inputs to a new array, with the key named by the input name attribute
if inputs[value] != nil && inputs[value].(*dom.HTMLInputElement).Value != "" {
data.Add(inputs[value].(*dom.HTMLInputElement).Name, inputs[value].(*dom.HTMLInputElement).Value)
}
}
req, _ := http.NewRequest(method, actionUrl, strings.NewReader(data.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")