无法在 http 请求中设置 POST 正文

这不是设置 POST 请求正文的正确方法吗?


data := url.Values{}

data.Set("url", "https://www.google.com/")


client := http.Client{}

r, err := http.NewRequest(http.MethodPost, apiURL, strings.NewReader(data.Encode()))

下面的代码执行时表明请求url param中未发送任何内容POST。


package main


import (

    "fmt"

    "io/ioutil"

    "net/http"

    "net/url"

    "strings"

)


func doAPICall() {

    // curl -XPOST -d 'url=https://www.google.com/' 'https://cleanuri.com/api/v1/shorten'

    apiURL := "https://cleanuri.com/api/v1/shorten"


    data := url.Values{}

    data.Set("url", "https://www.google.com/")


    client := http.Client{}

    r, err := http.NewRequest(http.MethodPost, apiURL, strings.NewReader(data.Encode()))

    if err != nil {

        panic(err)

    }

    resp, err := client.Do(r)

    if err != nil {

        panic(err)

    }

    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {

        panic(err)

    }

    fmt.Println(string(body))

}

func main() {

    doAPICall()

}

输出:-


$ go run .

{"error":"API Error: URL is empty"}


慕村9548890
浏览 160回答 2
2回答

慕容森

服务器期望 Content-Type 请求标头具有有效值。r, err := http.NewRequest(http.MethodPost, apiURL, strings.NewReader(data.Encode()))if err != nil {&nbsp; &nbsp; panic(err)}r.Header.Set("Content-Type", "application/x-www-form-urlencoded") // <-- add this lineresp, err := client.Do(r)服务器还支持 JSON 请求体:r, err := http.NewRequest(http.MethodPost, apiURL, strings.NewReader(`{"url": "https://www.google.com/"}`))if err != nil {&nbsp; &nbsp; panic(err)}r.Header.Set("Content-Type", "application/json")resp, err := http.DefaultClient.Do(r)

慕尼黑5688855

你可以做这样的事情package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io/ioutil"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; url := "https://cleanuri.com/api/v1/shorten"&nbsp; &nbsp; payload := strings.NewReader("url=https://www.google.com/")&nbsp; &nbsp; req, err := http.NewRequest("POST", url, payload)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; req.Header.Add("content-type", "application/x-www-form-urlencoded")&nbsp; &nbsp; req.Header.Add("cache-control", "no-cache")&nbsp; &nbsp; res, err := http.DefaultClient.Do(req)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; defer res.Body.Close()&nbsp; &nbsp; body, _ := ioutil.ReadAll(res.Body)&nbsp; &nbsp; fmt.Println(res)&nbsp; &nbsp; fmt.Println(string(body))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go