GO语言HTTP请求案例–httpUtil.go

package util

import (
“bytes”
“fmt”
“io/ioutil”
“log”
“net/http”
)

/*
发送的POST请求 需要设置header
Testner 20210123
/
func Post_Json(url string, bodyJson string,authorization string) string {

contentType := “application/json”

req,err := http.NewRequest(“POST”,url,bytes.NewBuffer([]byte(bodyJson)))

if err != nil {
log.Fatal(err)
}

req.Header.Set(“Authorization”, fmt.Sprintf(“Bearer %s”, authorization))
req.Header.Set(“Content-Type”, contentType)

resp ,err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}

byts,err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
log.Fatal(err)
}
return (string(byts))
}

/*
发送的GET请求 需要设置header
Testner 20210123
/
func Get_Json(url string, authorization string) string {

contentType := “application/json”

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

if err != nil {
log.Fatal(err)
}

req.Header.Set(“Authorization”, fmt.Sprintf(“Bearer %s”, authorization))
req.Header.Set(“Content-Type”, contentType)

resp ,err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}

byts,err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
log.Fatal(err)
}
return (string(byts))
}

Original: https://www.cnblogs.com/sea520/p/14329490.html
Author: sea的博客
Title: GO语言HTTP请求案例–httpUtil.go

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/535740/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球