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)

}

相关推荐
任风雨11 小时前
13.2.1.Apache HTTP Server
http·apache·web服务器
liubaoyi21711 小时前
网络原理--HTTP
网络·http
风语者日志12 小时前
[LitCTF 2023]作业管理系统
前端·网络·安全·web安全·ctf
盈创力和200714 小时前
物联网 “神经” 之以太网:温湿度传感器的工业级 “高速干道”
运维·服务器·网络·嵌入式硬件·以太网温湿度传感器
聪明努力的积极向上14 小时前
【C#】HTTP中URL编码方式解析
开发语言·http·c#
余生皆假期-15 小时前
IIC 通讯详解——以 OSI 模型分析 物理层、数据链路层和应用层
网络
李辉200315 小时前
Python逻辑运算符
java·网络·python
平凡而伟大(心之所向)15 小时前
TCP Socket(TCP 套接字)和 WebSocket 区别详解
websocket·网络协议·tcp/ip
火车叨位去194915 小时前
计算机网络R2025秋(TYUT)【计算机网络】第5章 运输层
网络·tcp/ip·计算机网络
huangql52015 小时前
HTTP协议与WebSocket完整技术指南
websocket·网络协议·http