golang·后端发起Get或POST请求
1】发出Get请求:
//请求=================== client := &http.Client{} resp, err := client.Get(url) //get请求链接 if err != nil { log.Fatal(err) } jsons, err := ioutil.ReadAll(resp.Body) //筛出json if err != nil { fmt.Println("用户登陆get 异常err") } defer resp.Body.Close() //存储到结构体============= type Obj struct { Openid string `json:"openid"` Session_key string `json:"session_key"` } var Objs Obj json.Unmarshal([]byte(jsons), &Objs) //json.Unmarshal([]byte(string(jsons)), &Objs) fmt.Println(Objs.Openid) //打印结果
返回 json
msg, _ := json.Marshal(Objs) //转换成json writer.Write(msg) //返回值 必须先定义异常 _:=
2】普通POST请求
resp, err := http.Post("https://aip.baidu.com/",//请求地址 "application/x-www-form-urlencoded",//请求头 strings.NewReader("access_token="+access_token+"&text="+text),//请求内容 ) if err != nil { fmt.Println("请异常:",err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("读取异常:",err) } fmt.Println(string(body)) //打印结果
3】httpPostForm 请求
func httpPostForm(text string) { //httpPostForm() access_token := "xxx27013614" posturl := "https://aip.baidu.com/" resp, err := http.PostForm(posturl, url.Values{"access_token": {access_token}, "text": {text}}) if err != nil { fmt.Println("请异常:", err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("读取异常:", err) } fmt.Println(string(body)) }
4】插入请求头
var urls = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token client := &http.Client{} resp, err := http.NewRequest("POST", urls, strings.NewReader("code="+code+"&aa=xxx")) if err != nil { fmt.Println("读取异常0: ", err) } resp.Header.Set("Content-Type", "application/json") //加入请求头设置 resp.Header.Set("code", code) //加入请求头设置 rep, err := client.Do(resp) if err != nil { fmt.Println("读取异常1: ", err) } defer rep.Body.Close() body, err := ioutil.ReadAll(rep.Body) //请求结果 if err != nil { fmt.Println("读取异常2: ", err) } fmt.Println(string(body)) //打印结果
5】发送JSON数据的post请求(请求头中插入数据)
client := &http.Client{} data := make(map[string]interface{}) data["code"] = "codexxx" data["id"] = "idxxx" bytesData, _ := json.Marshal(data) req, _ := http.NewRequest("POST","http://www.baidu.com",bytes.NewReader(bytesData)) resp, _ := client.Do(req) body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body))
例子:(获取微信登陆用户手机号码)
urls := "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token client := &http.Client{} //创建网络 data := make(map[string]interface{}) //构建键值对模式 data["code"] = code bytesData, _ := json.Marshal(data) //转json格式 req, _ := http.NewRequest("POST", urls, bytes.NewReader(bytesData)) //创建接口请求 resp, _ := client.Do(req) //发送接口请求 body, err := ioutil.ReadAll(resp.Body) //获得结果 if err != nil { fmt.Println("微信小程序用户手机号码 读取异常2: ", err) } fmt.Println(body) //打印结果
1,146 Views