package mainimport ( "bytes" "enCoding/Json" "fmt" "io/IoUtil" "net/http")func main(){ uI := httpPost("http:xxxxxx") fmt.Println(uI) user :=userInfo{} httpGet("http:xxxxxx?a=0&b=1&c=2",&user) fmt.Println(user)}type userInfo struct { Code int `Json:"code"` Data interface{} `Json:"data"` Msg string `Json:"msg"`}/*httpPost请求,获取userInfo,并将响应数据Json解析定义的结构*/func httpPost(url string) (uI userInfo) { data := map[string]interface{}{ "Firstname":"Jan", "Sex":18, } stu,_ := Json.Marshal(&data) reader := bytes.NewReader(stu) request,_ := http.NewRequest("POST", url, reader) request.header.Set("Content-Type", "application/Json") clIEnt:=&http.ClIEnt{} response,_ := clIEnt.Do(request) defer response.Body.Close() body,_ := IoUtil.ReadAll(response.Body) //已知结构解析 _ = Json.Unmarshal(body, &uI) /*//未知结构解析 var uI interface{} _ = Json.Unmarshal(body, &uI)*/ return uI}/*httpGet请求,并将响应数据Json解析定义的结构*/func httpGet(url string,data interface{}) interface{} { resp, err := http.Get(url) if err != nil { panic(err) } defer resp.Body.Close() err = Json.NewDecoder(resp.Body).Decode(&data) return data}总结
以上是内存溢出为你收集整理的go语音 post和get请求全部内容,希望文章能够帮你解决go语音 post和get请求所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)