go发送get或post请求
package main
import (
"bytes"
"crypto/md5"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"strconv"
"time"
)
func main() {
// GetData()
PostMethod()
}
//这是get请求
func GetData() {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} //如果需要测试自签名的证书 这里需要设置跳过证书检测 否则编译报错
client := &http.Client{Transport: tr}
resp, err := client.Get("https://192.168.7.15:8080/v1/getaction.do")
//此处需要注意经过测试,不论是否有err在此之前一定要判断resp.Body如果不为空则需要关闭,测试环境go1.16
if resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
fmt.Println("error:", err)
return
}
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
//这是post请求
func PostMethod() {
var rsp io.Reader
tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} //如果需要测试自签名的证书 这里需要设置跳过证书检测 否则编译报错
client := &http.Client{Transport: tr}
data := "cmd=123"
resp, err := client.Post("https://192.168.7.15:8080/v1/postaction.do", data, rsp)
//此处需要注意经过测试,不论是否有err在此之前一定要判断resp.Body如果不为空则需要关闭,测试环境go1.16
if resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
fmt.Println("err:", err)
} else {
body, er := ioutil.ReadAll(resp.Body)
if er != nil {
fmt.Println("err:", er)
} else {
fmt.Println(string(body))
}
}
}
func PostMethod() {
//{"carmeraId":"epark-370211-dongjiakou~~cctv-dahua~channelCode~dahua!1000003$1$0$6","carmeraDesc":"","status":"1","areaId":"001","dataTime":"2020-11-17 14:30:12"}
//{"carmeraId":"epark-370211-dongjiakou~~cctv-dahua~channelCode~dahua!1000003$1$0$7","carmeraDesc":"2F走廊西","status":"1","areaId":"001","dataTime":"2020-11-17 15:42:01"}
m3 := map[string]string{
"cameraId": "epark-370211-dongjiakou~~cctv-dahua~channelCode~dahua!1000003$1$0$7",
"cameraDesc": "2F走廊西",
"status": "1",
"areaId": "001",
"dataTime": "2020-11-17 15:42:01",
}
exportData, err := json.Marshal(m3)
tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
client := &http.Client{Transport: tr}
req, err := http.NewRequest(http.MethodPost, "https://eug-test.elinkit.com.cn/epmet-acs/report/video/info", bytes.NewReader(exportData))
if err != nil {
log.Fatal(err.Error)
}
times := strconv.FormatInt(time.Now().Unix(), 10)
data := []byte("c3c4029b9741f26ab4a4cbd98c2310ff" + times)
has := md5.Sum(data)
accessToken := fmt.Sprintf("%x", has)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("AccessToken", accessToken)
req.Header.Set("Timestamp", times)
response, err := client.Do(req)
//此处需要注意经过测试,不论是否有err在此之前一定要判断 response.Body 如果不为空则需要关闭,测试环境go1.16
if response.Body != nil {
defer response.Body.Close()
}
if err != nil {
fmt.Println("err:", err)
}
body, er := ioutil.ReadAll(response.Body)
if er != nil {
fmt.Println("err:", er)
}
fmt.Println(string(body))
}