我尝试在golang中发送这样的请求,但没有结果:
curl -s -i -H "Accept: application/json" "http://192.168.1.183:8080/json.htm?type=command&c=getauth¶m=udevice&idx=9&nvalue=0&svalue=10;43;2"
怎么做?
我想发送数据做Domoticz家庭自动化系统。 我得到了Anser:
{
"status" : "ERR"
}
但应该是:
{
"status" : "OK",
"title" : "Update Device"
}
我试试这段代码:
b := bytes.NewBufferString("type=command&c=getauth¶m=udevice&idx=9&nvalue=0&svalue=10;43;2")
res, _ := http.Post("http://192.168.1.183:8080/json.htm", "Accept: application/json", b)
答案 0 :(得分:3)
请注意,在您的初始curl
命令中,您错过了-X POST
参数
generated code将是:
// Generated by curl-to-Go: https://mholt.github.io/curl-to-go
req, err := http.NewRequest("POST", "http://192.168.1.183:8080/json.htm?type=command&c=getauth¶m=udevice&idx=9&nvalue=0&svalue=10;43;2", nil)
if err != nil {
// handle err
}
req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
// handle err
}
defer resp.Body.Close()
答案 1 :(得分:2)
你的curl命令和Go代码几乎完全不相同。
你的go代码的卷曲等效于:
curl -s -i -X POST -H "Accept: application/json" "http://192.168.1.183:8080/json.htm" -d "type=command&c=getauth¶m=udevice&idx=9&nvalue=0&svalue=10;43;2"
在Go中模拟curl命令的最简单方法是:
req, err := http.NewRequest("GET", "http://192.168.1.183:8080/json.htm?type=command&c=getauth¶m=udevice&idx=9&nvalue=0&svalue=10;43;2", nil)
if err != nil {
panic(err)
}
req.Header.Add("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
答案 2 :(得分:-2)
这对我有用:
b := bytes.NewBufferString(" ")
res, _ := http.Post("http://192.168.1.183:8080/json.htm?type=command&c=getauth¶m=udevice&idx=9&nvalue=0&svalue=10;43;2", "Accept: application/json", b)
但我认为这不是最佳方式。