美文网首页
golang http request汇总

golang http request汇总

作者: heliping_peter | 来源:发表于2021-10-21 18:00 被阅读0次
  1. 获取get的header
client := &http.Client{}
    reqest, err := http.NewRequest("GET", url, nil)
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    reqest.Header.Set("version", "1")
    resp, err := client.Do(reqest)//发送请求
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    defer resp.Body.Close()//一定要关闭resp.Body
    captcha_id := resp.Header.Get("captchaId")

2.使用application/x-www-form-urlencoded格式发送post请求

   form := url.Values{}
    form.Set("taskId", planid)  
    client := &http.Client{}//客户端,被Get,Head以及Post使用
    reqest, err := http.NewRequest("POST", urlj, strings.NewReader(form.Encode()))
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    reqest.Header.Set("Content-Type", "application/x-www-form-urlencoded")  
    resp, err := client.Do(reqest)//发送请求
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    defer resp.Body.Close()//一定要关闭resp.Body

3.发送post,body为json文件

func FeishuSend(message string) {
    var feishuWeebhook = config.CONFIG.GetString("feishu.group")
    sendmsg := make(map[string]interface{})
    mm := make(map[string]interface{})
    mm["text"] = message
    sendmsg["msg_type"] = "text"
    sendmsg["content"] = mm
    bytesData, err := json.Marshal(sendmsg)
    client := &http.Client{}
    reqest, err := http.NewRequest("POST", feishuWeebhook, bytes.NewReader(bytesData))
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    resp, err := client.Do(reqest)
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    defer resp.Body.Close()//一定要关闭resp.Body
    content, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    responscon := string(content)
    fmt.Printf("http请求返回:%+v\n", responscon)
}

相关文章

网友评论

      本文标题:golang http request汇总

      本文链接:https://www.haomeiwen.com/subject/cixqaltx.html