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)

}

相关推荐
海清河晏1116 分钟前
Linux进阶篇:HTTP协议
linux·运维·http
June`8 分钟前
IO模型全解析:从阻塞到异步(高并发的reactor模型)
linux·服务器·网络·c++
Tao____10 分钟前
如何对接Modbus-tcp协议(使用Thinlinks物联网平台)
java·物联网·网络协议·tcp/ip·modbus
乾元16 分钟前
如何把 CCIE / HCIE 的实验案例改造成 AI 驱动的工程项目——从“实验室能力”到“可交付系统”的完整迁移路径
大数据·运维·网络·人工智能·深度学习·安全·机器学习
liulilittle20 分钟前
俄罗斯访问欧洲国际线路优化
开发语言·网络·信息与通信·ip·通信·俄罗斯·莫斯科
菜择贰36 分钟前
计算机网络课设
网络·计算机网络·智能路由器
weixin79893765432...38 分钟前
深入浅出 WebSocket 协议
websocket·http·socket·sse
浅安的邂逅1 小时前
ubuntu 18.04及以上版本配置静态IP方法
linux·运维·网络·ubuntu·ip设置
阿巴~阿巴~1 小时前
从钓鱼到高性能服务器:深入解析操作系统五大 I/O 模型
运维·服务器·网络·系统调用·五种i/o模型
callJJ1 小时前
WebSocket 两种实现方式对比与入门
java·python·websocket·网络协议·stomp