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)

}

相关推荐
橘子真甜~6 小时前
C/C++ Linux网络编程15 - 网络层IP协议
linux·网络·c++·网络协议·tcp/ip·计算机网络·网络层
Allen正心正念20256 小时前
网络编程与通讯协议综合解析
网络
bing_feilong7 小时前
ubuntu中的WIFI与自身热点切换
网络
CodeByV7 小时前
【网络】UDP 协议深度解析:从五元组标识到缓冲区
网络·网络协议·udp
车载测试工程师7 小时前
CAPL学习-AVB交互层-概述
网络协议·tcp/ip·以太网·capl·canoe
虹科网络安全8 小时前
艾体宝洞察 | 利用“隐形字符”的钓鱼邮件:传统防御为何失效,AI安全意识培训如何补上最后一道防线
运维·网络·安全
石像鬼₧魂石8 小时前
Kali Linux 网络端口深度扫描
linux·运维·网络
鲸鱼电台分台9 小时前
工业应用通信协议:IEC104
网络协议
适应规律9 小时前
UNeXt-Stripe网络架构解释
网络
纸带11 小时前
USB通信的状态
网络