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)

}

相关推荐
Jony_2 天前
高可用移动网络连接
网络协议
chilix2 天前
Linux 跨网段路由转发配置
网络协议
DianSan_ERP4 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet
呉師傅4 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
gihigo19984 天前
基于TCP协议实现视频采集与通信
网络协议·tcp/ip·音视频
2501_946205524 天前
晶圆机器人双臂怎么选型?适配2-12寸晶圆的末端效应器有哪些?
服务器·网络·机器人
linux kernel4 天前
第七部分:高级IO
服务器·网络
数字护盾(和中)4 天前
BAS+ATT&CK:企业主动防御的黄金组合
服务器·网络·数据库
~远在太平洋~4 天前
Debian系统如何删除多余的kernel
linux·网络·debian
unfeeling_4 天前
Keepalived实验
linux·服务器·网络