我建立其執行POST到電報通道A golang應用程序中使用給定的機器人令牌,但是當我這樣做,我得到400錯誤的請求與Golang和電報API
400錯誤的請求
這是我的帖子:
import (
"fmt"
"net/url"
"net/http"
"strings"
)
. . .
request_url := "https://api.telegram.org/bot{token}/sendMessage?chat_id={channelId}"
urlData := url.Values{}
urlData.Set("text", "Hello!")
client := &http.Client{}
req, _ := http.NewRequest("POST", request_url, strings.NewReader(urlData.Encode()))
req.Header.Set("content-type", "application-json")
res, err := client.Do(req)
if(err != nil){
fmt.Println(err)
} else {
fmt.Println(res.Status)
}
我不明白爲什麼它給了我400甚至認爲我能夠執行同樣的POST使用郵差
POST https://api.telegram.org/bot{token}/sendMessage?chat_id={channelId}
body : {"text" : "Hello"} Content-Type=application/json
關於如何解決此問題的任何提示?
我一直在撓我的頭一陣子,但我無法解決這個問題。
UPDATE
試圖@old_mountain方法會導致同樣的結果
import (
"fmt"
"net/http"
"bytes"
"encoding/json"
)
request_url := "https://api.telegram.org/bot{token}/sendMessage?chat_id={channelId}"
client := &http.Client{}
values := map[string]string{"text": "Hello!"}
jsonStr, _ := json.Marshal(values)
req, _ := http.NewRequest("POST", request_url, bytes.NewBuffer(jsonStr))
req.Header.Set("content-type", "application-json")
res, err := client.Do(req)
if(err != nil){
fmt.Println(err)
} else {
fmt.Println(res.Status)
}
你不發送表單數據,而不是JSON在這裏? API似乎期望JSON – pvg
'strings.NewReader(urlData.Encode()'違背'req.Header.Set(「content-type」,「application-json」)' – Volker
@Volker,所以它會與**文本/純**正確嗎?爲了發送一個JSON像@pvg說什麼我必須改變?我想通過** var data string =「'{text:Hello}'」**而不是,但仍然沒有我很抱歉,如果這是微不足道的,但我是一個初學者 – AndreaM16