美文网首页
go 使用post调用https

go 使用post调用https

作者: 玄德公笔记 | 来源:发表于2022-03-01 16:57 被阅读0次

1. go 一个完整示例

  • 完整示例
package main

import (
    "bytes"
    "crypto/tls"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

func main() {
    //定义一个结构体传参
    var body struct {
        UserName string `json:"username"`
        Password string `json:"password"`
    }

    body.UserName = "liubei"
    body.Password = "3xxxxxxx"

    //定义harder,Content-Type后边函数里写了,这里不用写,定义空即可。
    headers := make(map[string]string)
    //headers["Content-Type"] = "application/json"

    //调用PostJSONWithResp函数,得到返回值
    statusCode,respBody,_ := PostJSONWithResp("https://10.10.xxx.159/api/v3/sessions",headers,
        body,
        time.Duration(time.Second*10))
    
    fmt.Println(statusCode,string(respBody))
}


func PostJSONWithResp(url string, headers map[string]string, data interface{}, timeout time.Duration) (statusCode int, respBody []byte, err error) {


    var jsonBytes []byte
    if bytes, ok := data.([]byte); ok {
        jsonBytes = bytes
    } else {
        if jsonBytes, err = json.Marshal(data); err != nil {
            return
        }
    }


    var req *http.Request
    if req, err = http.NewRequest("POST", url, bytes.NewBuffer(jsonBytes)); err != nil {
        return
    }
    req.Header.Set("Content-Type", "application/json")

    if headers != nil {
        for key, value := range headers {
            req.Header.Set(key, value)
        }
    }

    tr:=&http.Transport{TLSClientConfig:&tls.Config{InsecureSkipVerify:true}} //不验证ca证书,否则卡在这里
    client := &http.Client{Timeout: timeout,Transport:tr}
    resp, err := client.Do(req)
    if err != nil {
        return
    }
    defer resp.Body.Close()

    statusCode = resp.StatusCode
    respBody, _ = ioutil.ReadAll(resp.Body)

    return
}

  • 返回结果
200 {"user_id":"169f95ca-7899-4cb4-ace7-b7484d33901c","token":"xxxxxx","create_time":"2022-03-01T08:42:52.418108628Z","expire_time":"2022-03-08T08:42:52.418108825Z"}

  • body也可以用json定义
body := []byte(`{"username":"liuwei","password":"30gmcyt8Kllyhy"}`)

2. 附录

  • 只返回code
func PostJSON(url string, headers map[string]string, data interface{}, timeout time.Duration) (statusCode int, err error) {
    logger.Debugf("[httputils] PostJSON url: %s", url)

    var jsonBytes []byte

    if bytes, ok := data.([]byte); ok {
        jsonBytes = bytes
    } else {
        if jsonBytes, err = json.Marshal(data); err != nil {
            return
        }
    }

    logger.Debugf("[httputils] post data: %s", string(jsonBytes))

    var req *http.Request
    if req, err = http.NewRequest("POST", url, bytes.NewBuffer(jsonBytes)); err != nil {
        return
    }

    req.Header.Set("Content-Type", "application/json")
    if headers != nil {
        for key, value := range headers {
            req.Header.Set(key, value)
        }
    }

    client := &http.Client{Timeout: timeout}
    resp, err := client.Do(req)
    if err != nil {
        return
    }
    statusCode = resp.StatusCode

    return
}
  • get
func GetJSON(url string, headers map[string]string, timeout time.Duration) (respBody []byte, err error) {
    logger.Debugf("[HttpServer] GetJSON : %s", url)

    client := &http.Client{Timeout: timeout}

    req, err := http.NewRequest("GET", url, nil)

    if headers != nil {
        for key, value := range headers {
            req.Header.Set(key, value)
        }
    }

    var resp *http.Response
    resp, err = client.Do(req)

    if err == nil {
        defer resp.Body.Close()
        respBody, err = ioutil.ReadAll(resp.Body)
    }

    return
}

相关文章

网友评论

      本文标题:go 使用post调用https

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