dongzheng4556 2017-03-08 14:11
浏览 191
已采纳

使用Golang和Telegram API的400错误请求

I'm building a golang application which performs a POST to a Telegram Channel using a given Bot token but when I do it I get

400 Bad Request

This is my POST:

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

I don't get why it's giving me 400 even thought I'm able to perform the very same POST using Postman

POST https://api.telegram.org/bot{token}/sendMessage?chat_id={channelId}
body : {"text" : "Hello"} Content-Type=application/json

Any Hint on how to fix this?

I've been scratching my head for a while but I wasn't able to solve this.

UPDATE

Trying @old_mountain approach leads to the same result

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)
  }
  • 写回答

1条回答 默认 最新

  • douzi4724 2017-03-08 14:21
    关注

    You need to send a json string.

    var jsonStr = []byte(`{"text":"Hello!"}`)
    req, _ := http.NewRequest("POST", request_url, bytes.NewBuffer(jsonStr))
    

    Or, if you don't want to directly write it:

    values := map[string]string{"text": "Hello!"}
    jsonStr, _ := json.Marshal(values)
    req, _ := http.NewRequest("POST", request_url, bytes.NewBuffer(jsonStr))
    

    Also, adjust the header Content-Type to:

    req.Header.Set("Content-Type", "application/json")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?