Go 中的 POST 请求中发送 JSON 字符串
技术问答
290 人阅读
|
0 人回复
|
2023-09-12
|
我试着用 Apiary 并制作了一个通用模板JSON 发送到模拟服务器并使用以下代码:
$ H0 E6 b" g9 ^; I7 t1 f' l+ {6 ?) q8 P
- package mainimport "encoding/json" "fmt" "github.com/jmcvetta/napping" "log" "net/http")func main() url := "http://restapi3.apiary.io/notes" fmt.Println("URL:>",url) s := napping.Session{} h := &http.Header{} h.Set("X-Custom-Header","myvalue") s.Header = h var jsonStr = []byte(`{ "title": "Buy cheese and bread for breakfast."}`) var data map[string]json.RawMessage err := json.Unmarshal(jsonStr,&data) if err != nil fmt.Println(err) } resp,err := s.Post(url,&data,nil,nil) if err != nil log.Fatal(err) } fmt.Println("response Status:",resp.Status() fmt.Println("response Headers:",resp.HttpResponse().Header) fmt.Println("response Body:",resp.RawText()code]代码没有正确发送 JSON,但我不知道为什么。JSON 字符串每次调用都可以不同。我不能用它。Struct这个。! a3 h9 N7 _2 h7 N# h Q. x5 d/ L. M
- " c) L3 U4 w: B* X' |# V% ~, m
- 解决方案: 6 w0 I& ^- N' O( g' @% M
- 我不熟悉napping,但使用 Golang 的net/http包工作正常(play.golang):[code]func main() url := "http://restapi3.apiary.io/notes" fmt.Println("URL:>",url) var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`) req,err := http.NewRequest("
OST",url,bytes.NewBuffer(jsonStr)) req.Header.Set("X-Custom-Header","myvalue") req.Header.Set("Content-Type","application/json") client := &http.Client{} resp,err := client.Do(req) if err != nil panic(err) } defer resp.Body.Close() fmt.Println("response Status:",resp.Status) fmt.Println("response Headers:",resp.Header) body,_ := ioutil.ReadAll(resp.Body) fmt.Println("response Body:",string(body))}
! |7 ~- {; o9 ^ R" k |
|
|
|
|
|