golang post发送application/json数据到服务器
发布时间:2020-12-16 18:09:11 所属栏目:大数据 来源:网络整理
导读:import ( "net/http" "encoding/json" "fmt" "bytes" "io/ioutil" "unsafe") type JsonPostSample struct { } func (this *JsonPostSample) SamplePost() { song := make(map[string]interface{}) song["name"] = "李白" song["timelength"] = 128 song["aut
import ( "net/http" "encoding/json" "fmt" "bytes" "io/ioutil" "unsafe" ) type JsonPostSample struct { } func (this *JsonPostSample) SamplePost() { song := make(map[string]interface{}) song["name"] = "李白" song["timelength"] = 128 song["author"] = "李荣浩" bytesData,err := json.Marshal(song) if err != nil { fmt.Println(err.Error() ) return } reader := bytes.NewReader(bytesData) url := "http://localhost/echo.php" request,err := http.NewRequest("POST",url,reader) if err != nil { fmt.Println(err.Error()) return } request.Header.Set("Content-Type","application/json;charset=UTF-8") client := http.Client{} resp,err := client.Do(request) if err != nil { fmt.Println(err.Error()) return } respBytes,err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err.Error()) return } //byte数组直接转成string,优化内存 str := (*string)(unsafe.Pointer(&respBytes)) fmt.Println(*str) }http://www.cnblogs.com/hitfire/articles/6427033.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |