亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Go 使用 JSON 文件發出 POST 請求

使用 Go 使用 JSON 文件發出 POST 請求

Go
一只萌萌小番薯 2022-11-08 10:45:55
我對 Go 很陌生,四處尋找這個問題,但沒有找到任何東西,所以如果這是我錯過的重復,我深表歉意。我需要使用 Go 發送一個 POST 請求,并讓正文來自 JSON 文件。下面是來自https://golangtutorial.dev/tips/http-post-json-go/的代碼的修改版本,我將其用作起點。我在想我可以jsonData用我拉入的 JSON 文件替換 var,但我只是想知道這是否是正確的方法以及如何最好地做到這一點。謝謝!package mainimport (    "bytes"    "fmt"    "io/ioutil"    "net/http")func main() {    httpposturl := "https://reqres.in/api/users"    // I think this is the block I need to alter?:    var jsonData = []byte(`{        "name": "morpheus",        "job": "leader"    }`)    request, error := http.NewRequest("POST", httpposturl, bytes.NewBuffer(jsonData))    request.Header.Set("Content-Type", "application/json; charset=UTF-8")    client := &http.Client{}    response, error := client.Do(request)    if error != nil {        panic(error)    }    defer response.Body.Close()    fmt.Println("response Status:", response.Status)}
查看完整描述

2 回答

?
呼如林

TA貢獻1798條經驗 獲得超3個贊

要發布文件,請使用打開的文件作為 HTTP 請求正文:


f, err := os.Open("file.json")

if err != nil {

    log.Fatal(err)

}

defer f.Close()


httpposturl := "https://reqres.in/api/users"

request, err := http.NewRequest("POST", httpposturl, f)

if err != nil {

    log.Fatal(err)

}

request.Header.Set("Content-Type", "application/json; charset=UTF-8")


response, err := http.DefaultClient.Do(request)

if err != nil {

    log.Fatal(err)

}

defer response.Body.Close()


fmt.Println("response Status:", response.Status)


查看完整回答
反對 回復 2022-11-08
?
largeQ

TA貢獻2039條經驗 獲得超8個贊

注意:無論您想通過 http 協議發布什么(文字、文件、圖像甚至視頻等),實際上您都發布了字節流。這意味著您應該將要發布的任何內容視為二進制字節數組。


在您的情況下,您應該首先打開要發布的文件,并創建一個指向您的文件的 io.Reader 類型的實例。簡單代碼如下:


f, _ := os.Open("./my-file")

    

http.Post("https://example.com/api","application/json",f)


查看完整回答
反對 回復 2022-11-08
  • 2 回答
  • 0 關注
  • 211 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號