Golang中如何通过API调用发送JSON格式的请求体

Golang中如何通过API调用发送JSON格式的请求体

gid_token := r.Header.Get("Authorization")

		request_url_gid := r.RequestURI
		jmb_gid_url := gid_env_url + request_url_gid

		body :=r.Body
		fmt.Print("%T",body)
		c_type :=r.Header.Get("Content-Type")
		fmt.Println("c_type",c_type)
		req, _ := http.NewRequest("POST", jmb_gid_url,body)
		req.Header.Add("Authorization","xxxxxx")
		req.Header.Add("Content-Type","application/json")
		fmt.Println(req)
		resp, _ := http.DefaultClient.Do(req)
		defer resp.Body.Close()
		bodynew, _ := ioutil.ReadAll(resp.Body)
		fmt.Fprintf(w, "%s", bodynew)

更多关于Golang中如何通过API调用发送JSON格式的请求体的实战教程也可以访问 https://www.itying.com/category-94-b0.html

9 回复

对此感到抱歉。

更多关于Golang中如何通过API调用发送JSON格式的请求体的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用带有 JSON 注解的结构体。

我想发送JSON请求体,但它没有作为请求的一部分发送

谢谢 😊 我的版本:

req, err := http.NewRequest("POST", url, strings.NewReader(r.Form.Encode()))

我有一个问题:即使值为空,我该如何仅将字段发送到API?

请编辑您的帖子,并将每行代码缩进四个空格。</> 按钮将帮助您完成此操作。

没问题。

关于你的问题:你刚刚发布了一段代码片段,但没有告诉我们这段代码应该做什么,它是否按照你的预期运行,或者是否存在任何问题或错误。你的具体问题是什么?

	// q 是你的结构体
    // url 是你的 url.URL

body := &bytes.Buffer{}
if err := json.NewEncoder(body).Encode(&q); err != nil {
	panic(err)
}

req, err := http.NewRequest(http.MethodPost, url.String(), body)

在Golang中通过API调用发送JSON格式的请求体,你的代码有几个问题需要修正。主要问题是直接使用了原始请求的r.Body作为新请求的body,这可能导致数据读取问题,并且没有正确处理JSON数据的序列化。

以下是修正后的代码示例:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    // 获取授权令牌
    gid_token := r.Header.Get("Authorization")
    
    // 构建目标URL
    request_url_gid := r.RequestURI
    jmb_gid_url := gid_env_url + request_url_gid
    
    // 读取原始请求体
    originalBody, err := ioutil.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Failed to read request body", http.StatusInternalServerError)
        return
    }
    defer r.Body.Close()
    
    // 验证并处理JSON数据
    var jsonData interface{}
    if err := json.Unmarshal(originalBody, &jsonData); err != nil {
        http.Error(w, "Invalid JSON in request body", http.StatusBadRequest)
        return
    }
    
    // 重新序列化JSON确保格式正确
    jsonBytes, err := json.Marshal(jsonData)
    if err != nil {
        http.Error(w, "Failed to marshal JSON", http.StatusInternalServerError)
        return
    }
    
    // 创建新的请求体
    body := bytes.NewBuffer(jsonBytes)
    
    // 创建HTTP请求
    req, err := http.NewRequest("POST", jmb_gid_url, body)
    if err != nil {
        http.Error(w, "Failed to create request", http.StatusInternalServerError)
        return
    }
    
    // 设置请求头
    req.Header.Add("Authorization", gid_token) // 使用实际的授权令牌
    req.Header.Add("Content-Type", "application/json")
    
    // 发送请求
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        http.Error(w, "Failed to send request", http.StatusInternalServerError)
        return
    }
    defer resp.Body.Close()
    
    // 读取响应
    bodynew, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        http.Error(w, "Failed to read response", http.StatusInternalServerError)
        return
    }
    
    // 返回响应
    w.Header().Set("Content-Type", "application/json")
    fmt.Fprintf(w, "%s", bodynew)
}

如果你有具体的结构体类型,可以使用类型化的JSON序列化:

// 定义请求数据结构
type RequestData struct {
    Name  string `json:"name"`
    Email string `json:"email"`
    Age   int    `json:"age"`
}

// 在handler函数中使用
func handlerWithStruct(w http.ResponseWriter, r *http.Request) {
    // 解析原始请求的JSON数据
    var requestData RequestData
    if err := json.NewDecoder(r.Body).Decode(&requestData); err != nil {
        http.Error(w, "Invalid JSON data", http.StatusBadRequest)
        return
    }
    defer r.Body.Close()
    
    // 序列化为JSON
    jsonBytes, err := json.Marshal(requestData)
    if err != nil {
        http.Error(w, "Failed to marshal JSON", http.StatusInternalServerError)
        return
    }
    
    // 创建请求体并发送请求
    body := bytes.NewBuffer(jsonBytes)
    req, err := http.NewRequest("POST", jmb_gid_url, body)
    if err != nil {
        http.Error(w, "Failed to create request", http.StatusInternalServerError)
        return
    }
    
    req.Header.Add("Authorization", gid_token)
    req.Header.Add("Content-Type", "application/json")
    
    // 其余代码与上面相同...
}

关键改进点:

  1. 正确读取和关闭原始请求体
  2. 验证JSON格式有效性
  3. 使用bytes.Buffer创建新的请求体
  4. 添加了错误处理
  5. 确保Content-Type正确设置为application/json
回到顶部