Unable to set POST body in a http request

六眼飞鱼酱① 提交于 2021-01-05 09:48:54

问题


Is this not the right way to set POST request body?

data := url.Values{}
data.Set("url", "https://www.google.com/")

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

The code below when executed suggests that no url param was sent in the POST request.

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()
}

Output:-

$ go run .
{"error":"API Error: URL is empty"}
$ 

回答1:


The server expects a valid value for the Content-Type request header.

r, err := http.NewRequest(http.MethodPost, apiURL, strings.NewReader(data.Encode()))
if err != nil {
    panic(err)
}
r.Header.Set("Content-Type", "application/x-www-form-urlencoded") // <-- add this line
resp, err := client.Do(r)

The server also supports JSON request bodies:

r, err := http.NewRequest(http.MethodPost, apiURL, strings.NewReader(`{"url": "https://www.google.com/"}`))
if err != nil {
    panic(err)
}
r.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(r)



回答2:


You can do something like this

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

func main() {

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

    payload := strings.NewReader("url=https://www.google.com/")

    req, err := http.NewRequest("POST", url, payload)
    if err != nil {
        fmt.Println(err)
        return
    }

    req.Header.Add("content-type", "application/x-www-form-urlencoded")
    req.Header.Add("cache-control", "no-cache")

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}


来源:https://stackoverflow.com/questions/57780438/unable-to-set-post-body-in-a-http-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!