当前位置: 首页 > 工具软件 > gohttp > 使用案例 >

go http.NewRequest用法

狄峰
2023-12-01

导入
import (
“bytes”
“crypto/tls”
“encoding/json”
“fmt”
“io/ioutil”
“log”
“net/http”
“reflect”
“time”
)

func main(){

type User struct {
	Username string `json:"username"`
	Password string `json:"password"`
}
urlSign := "https://ip:port"
user := User{"user","pwd"}
userNew,err :=json.Marshal(&user)
if err != nil{
	log.Println("失败", err)
	return
}
**//https跳过证书验证**
tr := &http.Transport{
	TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Timeout: 30 * time.Second, Transport: tr}
**//http不需要证书验证,直接写**
//client := &http.Client
reqUser := bytes.NewReader(userNew)
**//POST 请求需要加参数**
req, _ := http.NewRequest("POST", urlSign, reqUser)
**//GET 请求**
//req, _ := http.NewRequest("GET", urlSign, nil)
**//可以添加多个头部**
req.Header.Set("Content-Type", "application/json")
resp, _ := client.Do(req)
defer resp.Body.Close()
repBody, _ := ioutil.ReadAll(resp.Body)
**//可以根据repBody的数据类型获取数据**
//string
log.Println(string(repBody))
//map
var result map[string]interface{}
err1 := json.Unmarshal(repBody, &result)
if err1 != nil{
	log.Println(err1)
	return
}
log.Println(result)
//struct
type Test struct {
	//需要知道转换的字段和格式
	User string `json:"user"`
}
var test Test
err = json.UnMarshal(repBody, &test)
fmt.Println(json.MarshalIndent(test))

}

 类似资料: