//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”、“无效字符 'ï' 正在寻找值的开头”。
似乎数据没有正确解码。
虽然下面的代码有效
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)
最佳答案
请检查您的服务器要求的content-type
,并按照content-type
要求构建正文。
因为你的content-type
是application/json; charset=utf-8
,你试试手动设置
req.Header.Set("Content-Type", "application/json; charset=utf-8")
如果还是不行,请抓取http负载。
关于http - golang,从文件中读取内容,并在 HTTP 请求中作为正文数据发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34868502/