Post 在 go 中请求数据
Post request with data in go
我正在尝试像这样访问 API:
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
func main() {
apiUrl := "https://example.com/api/"
data := url.Values{}
data.Set("api_token", "MY_KEY")
data.Add("action", "list_projects")
req, _ := http.NewRequest("POST", apiUrl, bytes.NewBufferString(data.Encode()))
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err == nil {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.Status)
fmt.Println(string(body))
}
}
但是 API 的响应告诉我 POST 请求中没有数据。
如果我用 curl 这样做,它会起作用:
$ curl -X POST "https://example.com/api/" -d "api_token=MY_KEY" -d "action=list_projects"
您可能希望使用这种形式的请求
resp, err := http.PostForm("http://example.com/form",
url.Values{"key": {"Value"}, "id": {"123"}})
或使用正确的 mime 类型:
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
并对数据进行编码
strings.NewReader(data.Encode())
最好测试 err != nil 并在必要时测试 return。此代码可能无法工作,因为请求失败。
defer resp.Body.Close()
改为使用此模式:
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.Status)
fmt.Println(string(body))
所以你可以在控制台看到请求是否失败
我正在尝试像这样访问 API:
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
func main() {
apiUrl := "https://example.com/api/"
data := url.Values{}
data.Set("api_token", "MY_KEY")
data.Add("action", "list_projects")
req, _ := http.NewRequest("POST", apiUrl, bytes.NewBufferString(data.Encode()))
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err == nil {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.Status)
fmt.Println(string(body))
}
}
但是 API 的响应告诉我 POST 请求中没有数据。
如果我用 curl 这样做,它会起作用:
$ curl -X POST "https://example.com/api/" -d "api_token=MY_KEY" -d "action=list_projects"
您可能希望使用这种形式的请求
resp, err := http.PostForm("http://example.com/form",
url.Values{"key": {"Value"}, "id": {"123"}})
或使用正确的 mime 类型:
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
并对数据进行编码
strings.NewReader(data.Encode())
最好测试 err != nil 并在必要时测试 return。此代码可能无法工作,因为请求失败。
defer resp.Body.Close()
改为使用此模式:
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.Status)
fmt.Println(string(body))
所以你可以在控制台看到请求是否失败