【问题标题】:golang, read contents from file, and send as body data in HTTP requestgolang,从文件中读取内容,并在 HTTP 请求中作为正文数据发送
【发布时间】:2016-01-19 04:25:45
【问题描述】:
//read data from a file config.json
//the contents of config.json is
//{"key1":"...Z-DAaFpGT0t...","key2":"..."}
 client :=   &http.Client{}
 dat, err := ioutil.ReadFile("/config.json")
 req, err := http.NewRequest("PUT", url, bytes.NewBuffer(dat))
 resp, err := client.Do(req)

然后我会从服务器收到错误消息“400 Bad Request”、““invalid character 'ï' looking for beginning of value”。

数据似乎没有正确解码。

虽然下面的代码有效

 client :=   &http.Client{}
 //dat, err := ioutil.ReadFile("/config.json")
 var dat = []byte(`{"key1":"...Z-DAaFpGT0t...","key2":"..."}`)
 req, err := http.NewRequest("PUT", url, bytes.NewBuffer(dat))
 resp, err := client.Do(req)

【问题讨论】:

  • 你在检查那些错误吗?
  • 可以分享/config.json的内容吗?

标签: http go filereader


【解决方案1】:

请检查content-type您的服务器是否需要,并将主体构建为content-type需要。

因为你的content-typeapplication/json; charset=utf-8,你尝试手动设置它

req.Header.Set("Content-Type", "application/json; charset=utf-8")

如果仍然无法正常工作,请进行 http 负载捕获。

【讨论】:

  • 你的服务器需要什么content-type
  • 应用程序/json; charset=utf-8
猜你喜欢
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多