Post 使用Golang和电报API的400错误请求

Post 使用Golang和电报API的400错误请求,post,go,telegram-bot,Post,Go,Telegram Bot,我正在构建一个golang应用程序,它使用给定的Bot令牌对电报通道执行POST,但当我这样做时,我得到了 400错误请求 这是我的帖子: import ( "fmt" "net/url" "net/http" "strings" ) . . . request_url := "https://api.telegram.org/bot{token}/sendMessage?chat_id={channelId}" urlData := url.Values{}

我正在构建一个golang应用程序,它使用给定的Bot令牌对电报通道执行POST,但当我这样做时,我得到了

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 https://api.telegram.org/bot{token}/sendMessage?chat_id={channelId}
body : {"text" : "Hello"} Content-Type=application/json
有没有关于如何解决此问题的提示?

我挠头已经有一段时间了,但我没能解决这个问题

更新

尝试@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字符串

var jsonStr = []byte(`{"text":"Hello!"}`)
req, _ := http.NewRequest("POST", request_url, bytes.NewBuffer(jsonStr))
或者,如果您不想直接编写:

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")

您不是在这里发送表单数据而不是JSON吗?API似乎期望JSON
strings。NewReader(urlData.Encode()
req.Header.Set(“内容类型”,“应用程序JSON”)
@Volker相矛盾,所以它是文本/纯文本对的?为了发送类似@pvg的JSON,我说我必须更改什么?我正在尝试传递var数据字符串=“
{text:Hello}
”取而代之,但仍然不起作用。如果这是琐碎的话,我很抱歉,但我是一个初学者。仍然收到错误的请求。@AndreaM16您调整了标题了吗?现在它起作用了。我没有用正确的方式写它。