golang 写一段http post获取json 并解析
以下是使用golang编写的获取json并解析的http post请求示例:
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
type Response struct {
Message string `json:"message"`
}
func main() {
url := "https://example.com/api"
data := map[string]string{"name": "John", "age": "30"}
payload, err := json.Marshal(data)
if err != nil {
panic(err)
}
resp, err := http.Post(url, "application/json", strings.NewReader(string(payload)))
if err != nil {
panic(err)
}
defer resp.Body.Close()
var response Response
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
panic(err)
}
fmt.Println(response.Message)
}
在此示例中,我们首先定义了一个名为 Response 的结构,该结构包含一个名为 Message 的字符串字段。然后,我们定义了一个名为 data 的映射,其中包含名为 name 和 age 的两个键值对。
接下来,我们使用 json.Marshal 函数将数据映射转换为json格式的字符串。然后,我们使用http.Post函数向指定的url发送POST请求,并将json字符串作为请求正文发送。我们还指定了请求的Content-Type标头为“application/json”。
在响应中,我们使用 json.NewDecoder 函数将响应体解析为Response结构。最后,我们打印Message字段的值。
请注意,上述示例中的代码仅适用于POST请求,并且假定响应的内容类型为JSON。如果响应包含其他类型的数据或使用不同的HTTP方法(如GET或PUT)进行请求,则需要调整代码以适应这些情况
原文地址: https://www.cveoy.top/t/topic/fQMK 著作权归作者所有。请勿转载和采集!