GO语言用http包发送带json文本body的GET请求

$curl http://192.168.1.99:8089/devices -X GET -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{"nodeName": "192.168.1.111","containerId": "579"}'

{"status":1,"message":"ok","data":{"gpuId":5,"devUUID":"GPU-34dfc5f0-f402-900b-9e86-626a85d69686"}}
package main

import (

"bytes"

"encoding/json"

"fmt"

"io/ioutil"

"net/http"

)

type DeviceRequest struct {

NodeName string `json:"nodeName"`

ContainerId string `json:"containerId"`

}

type ApiResponse struct {

Status int `json:"status"`

Message string `json:"message"`

Data struct {

GpuId int `json:"gpuId"`

DevUUID string `json:"devUUID"`

} `json:"data"`

}

func main() {

// 创建请求数据

requestData := DeviceRequest{

NodeName: "192.168.1.111",

ContainerId: "d545d2da",

}

// 将请求数据序列化为JSON

jsonData, err := json.Marshal(requestData)

if err != nil {

fmt.Println("Error marshalling request data:", err)

return

}

// 创建HTTP请求

url := "http://192.168.1.99:8089/devices"

req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonData))

if err != nil {

fmt.Println("Error creating request:", err)

return

}

// 设置请求头

req.Header.Set("Content-Type", "application/json")

req.Header.Set("Accept", "application/json")

// 发送请求

client := &http.Client{}

resp, err := client.Do(req)

if err != nil {

fmt.Println("Error sending request:", err)

return

}

defer resp.Body.Close()

// 读取响应数据

body, err := ioutil.ReadAll(resp.Body)

if err != nil {

fmt.Println("Error reading response body:", err)

return

}

// 解析响应数据

var apiResponse ApiResponse

err = json.Unmarshal(body, &apiResponse)

if err != nil {

fmt.Println("Error unmarshalling response body:", err)

return

}

// 打印响应数据

fmt.Printf("%+v\n", apiResponse)

}

相关推荐
captain3763 小时前
网络初 识
运维·服务器·网络
ZzzZZzzzZZZzzzz…3 小时前
K8s---网络:从 Pod 网络模型到 Calico 三种模式
运维·网络·云原生·容器·kubernetes·calico·pod网络模型
国科安芯4 小时前
基于抗辐射MCU的卫星分布式控制系统CANFD总线架构研究
网络·人工智能·分布式·单片机·嵌入式硬件·架构·抗辐射
春风解人意12 小时前
从零开始学习嵌入式P32----网络基础之TCP
c语言·网络·学习·tcp/ip
云絮.13 小时前
网络原理---- 网络层,数据链路层,应用层
网络
Johny_Zhao14 小时前
网络安全等级保护测评实施方案
linux·网络·人工智能·网络安全·信息安全·云计算·等保测评·系统运维·itsm
虹科网络安全16 小时前
使用艾体宝 IOTA 10 CORE+ 监控企业网络中的 AI 流量
网络·人工智能
醉颜凉16 小时前
网络安全必学:粘性MAC地址(Sticky MAC)原理与应用全解析
运维·服务器·网络·安全·web安全
广州灵眸科技有限公司17 小时前
从手动三步到上电即连:4G模组systemd开机自连方案
linux·运维·服务器·开发语言·网络·人工智能·php
埃科光电18 小时前
16K万兆网口彩色线阵相机:四倍带宽 高速真彩检测新方案
网络·图像处理·数码相机·计算机视觉·制造·相机